Я создаю менеджер для своей оболочки Vulkan и имею следующую настройку. Все работает нормально, за исключением функций to_derived и to_base ниже, которые, как я подозреваю, могут иметь неопределенное поведение (UB). Мои вопросы: это на самом деле UB? Небезопасны ли они на практике (плохая ли это идея, и если нет, то почему)? И если да, то как я могу их исправить?
/* This is the interface for vku_* objects */
struct vku_object_t {
virtual ~vku_object_t() { _uninit(); }
template
friend struct vku_ref_t;
private:
virtual void _init() = 0;
virtual void _uninit() { return VK_SUCCESS; };
};
/* This structure is the only holder of data inside a reference */
struct vku_ref_base_t : public std::enable_shared_from_this {
protected:
/*! This is here to force the creation of references by create_obj_ref(...) */
struct private_param_t { explicit private_param_t() = default; };
std::unique_ptr _obj;
std::vector _dependees;
public:
template
vku_ref_base_t(private_param_t, std::unique_ptr obj) : _obj(std::move(obj)) {}
template
friend struct vku_ref_t;
virtual ~vku_ref_base_t() {}
virtual void rebuild() = 0;
virtual void clean_deps() = 0;
virtual void init_all() = 0;
virtual void uninit_all() = 0;
};
/*! This holds a reference to an instance of VkuT, instance that is initiated and held by this
* library. All objects and the user will use the instance via this reference. */
template
class vku_ref_t : public vku_ref_base_t {
protected:
void uninit_all() override {
clean_deps(); /* we lazy clear the deps whenever we want to iterate over them */
for (auto wd : _dependees)
wd.lock()->uninit_all();
_obj->_uninit();
}
void init_all() override {
_obj->_init();
for (auto wd : _dependees)
wd.lock()->init_all();
}
public:
vku_ref_t(private_param_t t, std::unique_ptr obj)
: vku_ref_base_t(t, std::move(obj)) {}
VkuT *get() { return static_cast(_obj.get()); }
template requires std::derived_from
std::shared_ptr to_base() {
return std::shared_ptr(
shared_from_this(), reinterpret_cast(this));
}
template requires std::derived_from
std::shared_ptr to_derived() {
return std::shared_ptr(
shared_from_this(), reinterpret_cast(this));
}
void clean_deps() override {
_dependees.erase(std::remove_if(_dependees.begin(), _dependees.end(), [](auto wp){
return wp.expired(); }), _dependees.end());
}
void rebuild() override {
/* TODO: maybe thread-protect this somehow? */
uninit_all();
init_all();
}
static std::shared_ptr create_obj_ref(std::unique_ptr obj,
std::vector dependencies)
{
auto ret = std::make_shared(private_param_t{}, std::move(obj));
for (auto &d : dependencies)
d->_dependees.push_back(ret);
return ret;
}
};
Подробнее здесь: https://stackoverflow.com/questions/797 ... mon-parent