为什么调用shared_from_this调用std :: terminate

Edu*_*yan 2 c++ shared-ptr c++-standard-library c++11 c++17

考虑以下代码:

class A : public std::enable_shared_from_this<A>
{
public:
     std::shared_ptr<A> f()
     {
          return shared_from_this();
     }
};

int main()
{
    A a;
    std::shared_ptr<A> ptr = a.f();
}
Run Code Online (Sandbox Code Playgroud)

此代码在Visual Studio 2017中终止.我想我在这里做错了.谁能帮我这个?我想在shared_from_this()创建的shared_ptr上.

lll*_*lll 7

因为a不是共享指针所拥有的.从cppreference:

允许仅在先前共享的对象上调用shared_from_this,即在由std :: shared_ptr管理的对象上.否则行为是未定义的(直到C++ 17)抛出std :: bad_weak_ptr(由默认构造的weak_this中的shared_ptr构造函数)(因为C++ 17).


Rak*_*111 5

您不能用于shared_from_this生成新的共享指针.您必须拥有一个现有的共享指针才能获得一个新指针:

std::shared_ptr a(new A());
auto ptr = a->f(); // ok, 'ptr' shares ownership of newed object with 'a'
Run Code Online (Sandbox Code Playgroud)

  • "_你不能 - "如果可以的话,这将是灾难性的! (2认同)