这个技巧是否会使在构造函数 'just work' 中调用 shared_from_this() 变得危险?
Is this trick, to make calling shared_from_this() in the constructor 'just work', dangerous?
C++ 专家的问题。
我们都知道在class构造函数中调用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,为我指明了正确的方向。
那不危险。
记录的限制是:cppreference
Before calling shared_from_this
, there should be at least one std::shared_ptr
p
that owns
*this
没有任何地方说它不能从构造函数内部使用/因为这个原因/。
这只是一个典型。这是因为在 正常 情况下, make_shared
或 shared_pointer<T>(new T)
无法在 T
构造函数退出之前完成。
警告:该对象未完全形成,因此您不能合法 调用任何虚拟方法(代价是Undefined Behaviour)。
指南 因为有可能错误地使用这个 class(例如,使用 shared_ptr<T>(new T)
会创建第二个具有相同底层指针的 shared_ptr值...哎呀)你应该更喜欢防止这种情况的设计。
Using a friend factory function that returns the shared_ptr<T>
could be one approach.
--> 另见 The Pit Of Success
C++ 专家的问题。
我们都知道在class构造函数中调用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,为我指明了正确的方向。
那不危险。
记录的限制是:cppreference
Before calling
shared_from_this
, there should be at least onestd::shared_ptr
p
that owns*this
没有任何地方说它不能从构造函数内部使用/因为这个原因/。
这只是一个典型。这是因为在 正常 情况下, make_shared
或 shared_pointer<T>(new T)
无法在 T
构造函数退出之前完成。
警告:该对象未完全形成,因此您不能合法 调用任何虚拟方法(代价是Undefined Behaviour)。
指南 因为有可能错误地使用这个 class(例如,使用 shared_ptr<T>(new T)
会创建第二个具有相同底层指针的 shared_ptr值...哎呀)你应该更喜欢防止这种情况的设计。
Using a friend factory function that returns the
shared_ptr<T>
could be one approach.
--> 另见 The Pit Of Success