这个技巧,是在构造函数中调用shared_from_this()"只是工作",这很危险吗?

Pau*_*oux 6 c++ constructor this shared-ptr

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() {}
};
Run Code Online (Sandbox Code Playgroud)

有人认为这不安全,因为该对象尚未完全形成.他是对的吗?

我没有使用'this'来访问成员变量或函数.此外,只要我使用了初始化列表,所有成员变量都已初始化.我不知道这招可能不安全.

编辑:事实证明这个技巧确实会造成不必要的副作用.在shared_from_this()将指向临时shared_ptr,如果你不小心,在我的示例代码中的父子关系将打破.执行enable_shared_from_this()只是不允许它.谢谢,Sehe,指出我正确的方向.

seh*_*ehe 5

那并不危险。

记录在案的限制是:cppreference

在调用之前shared_from_this,应该至少有一个std::shared_ptr p拥有 *this

没有任何地方说它不能从构造函数内部使用/出于这个原因/。

这只是一个典型的。那是因为在正常情况下,amake_sharedshared_pointer<T>(new T)无法在T构造函数退出。

警告:对象尚未完全成形,因此您不能合法地调用任何虚拟方法(以Undefined Behavior为代价)。


指南由于可能会错误地使用此类(例如,使用shared_ptr<T>(new T)它创建具有相同底层指针值的第二个 shared_ptr... 哎呀),您应该更喜欢防止这种情况的设计。

使用返回 的友元工厂函数shared_ptr<T>可能是一种方法。

--> 另见成功之坑

  • 现在的措辞不同了:“特别是,在构造‘*this’期间不能调用‘shared_from_this’” (2认同)