Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why calling shared_from_this calls std::terminate

Consider this code:

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();
}

This code terminated in Visual Studio 2017. I guess I am doing something wrong here. Can anyone help me with this? I want a shared_ptr on a created by shared_from_this().

like image 390
Eduard Rostomyan Avatar asked May 08 '26 04:05

Eduard Rostomyan


1 Answers

Because a is not a owned by a shared pointer. From cppreference:

It is permitted to call shared_from_this only on a previously shared object, i.e. on an object managed by std::shared_ptr. Otherwise the behavior is undefined (until C++17)std::bad_weak_ptr is thrown (by the shared_ptr constructor from a default-constructed weak_this) (since C++17).

like image 50
llllllllll Avatar answered May 09 '26 19:05

llllllllll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!