【发布时间】:2016-11-19 00:57:27
【问题描述】:
如您所知,不可能从对象的构造函数中使用 std::enable_shared_from_this 和 shared_from_this() 对,因为包含该类的 shared_pointer 尚不存在。但是,我真的很想要这个功能。我尝试了自己的系统,它似乎工作正常。
namespace kp
{
template <class T>
void construct_deleter(T *t)
{
if(!t->_construct_pself)
{
t->~T();
}
free(t);
}
template <class T, typename... Params>
std::shared_ptr<T> make_shared(Params&&... args)
{
std::shared_ptr<T> rtn;
T *t = (T *)calloc(1, sizeof(T));
t->_construct_pself = &rtn;
rtn.reset(t, construct_deleter<T>);
t = new(t) T(std::forward<Params>(args)...);
t->_construct_pself = NULL;
t->_construct_self = rtn;
return rtn;
}
template <class T>
class enable_shared_from_this
{
public:
std::shared_ptr<T> *_construct_pself;
std::weak_ptr<T> _construct_self;
std::shared_ptr<T> shared_from_this()
{
if(_construct_pself)
{
return *_construct_pself;
}
else
{
return _construct_self.lock();
}
}
};
}
谁能发现这个逻辑中的任何缺陷?在构造函数调用之前,我基本上使用placement new 来分配指向类中shared_ptr 的指针。
就目前而言,我可以这样使用它:
std::shared_ptr<Employee> emp = kp::make_shared<Employee>("Karsten", 30);
在 Employee 构造函数中:
Employee::Employee(std::string name, int age)
{
Dept::addEmployee(shared_from_this());
}
在我将它提交到一个相对较大的代码库之前,我非常感谢你们的一些想法或反馈。
谢谢!
【问题讨论】:
-
您只能通过您的自定义
make_shared创建这些;如果您尝试使用任何其他形式的初始化,它将在运行时失败。只需使用提供创建实例的静态create()函数的标准模式,然后在返回它之前执行任何需要shared_from_this()的操作。 -
抱歉,这种代码不可能通过我团队的审查。你不能想出一个更简单和自我记录的设计吗?您真正试图解决的问题是什么?为什么传统方法不能满足该目标?
标签: c++ memory shared-ptr