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,指出我正确的方向。
答案 0 :(得分:4)
那不危险。
记录的限制是:cppreference
在致电
shared_from_this
之前,应至少有一个std::shared_ptr
p
拥有*this
没有任何地方说它不能在构造函数内使用/出于这个原因/.
这只是一个典型的。这是因为在正常情况下,make_shared
或shared_pointer<T>(new T)
无法在T
构造函数退出之前完成。
警告:对象未完全形成,因此您无法合法地调用任何虚拟方法(以Undefined Behaviour为代价)。
指南由于可能使用此类错误(例如使用shared_ptr<T>(new T)
创建第二个具有相同底层指针值的shared_ptr ... oops)您应该更喜欢防止设计此
使用返回
shared_ptr<T>
的友元工厂函数可能是一种方法。
- &GT;另请参阅The Pit Of Success