【发布时间】:2016-01-09 06:09:05
【问题描述】:
C++ 专家的问题。
我们都知道在类构造函数中调用 shared_from_this() 会导致 bad_weak_ptr 异常,因为还没有创建实例的 shared_ptr。
为了解决这个问题,我想出了这个技巧:
class MyClass : public std::enable_shared_from_this<MyClass>
{
public:
MyClass() {}
MyClass( const MyClass& parent )
{
// Create a temporary shared pointer with a null-deleter
// to prevent the instance from being destroyed when it
// goes out of scope:
auto ptr = std::shared_ptr<MyClass>( this, [](MyClass*){} );
// We can now call shared_from_this() in the constructor:
parent->addChild( shared_from_this() );
}
virtual ~MyClass() {}
};
有人认为这是不安全的,因为该物体尚未完全成型。他说的对吗?
我没有使用“this”来访问成员变量或函数。此外,只要我使用了初始化列表,所有成员变量都已经初始化。我不明白这个技巧怎么会不安全。
编辑:事实证明这个技巧确实会产生不必要的副作用。 shared_from_this() 将指向临时的shared_ptr,如果你不小心,我的示例代码中的父子关系将会中断。 enable_shared_from_this() 的实现根本不允许。谢谢,Sehe,为我指明了正确的方向。
【问题讨论】:
-
使用静态工厂函数调用 make_shared 并进行添加可能会更好地处理。这种方式对正确性没有歧义。
-
解决这个问题的一种方法是
MyClass temp(myparent);局部变量刚刚被填充到共享指针中。 -
这确实是我过去的处理方式(见下文),但我希望我能让它“正常工作”。
static std::shared_ptr<MyClass> create() { /* "initialize" would contain a call to shared_from_this() */ auto ptr = std::make_shared<MyClass>(); ptr->initialize(); return ptr; }
标签: c++ constructor this shared-ptr