简体   繁体   中英

CRTP base class inheriting std::enable_shared_from_this, throwing std::bad_weak_ptr. I need quidance

When I try to share_from_this() in the base class shared_handler to return a DerivedT shared pointer, I get an exception thrown: std::bad_weak_ptr

I have tried storing an internal shared pointer in the base class, during construction, before ever calling shared_from_this() , but I get an even more ambiguous error.

template<class DerivedT>
struct shared_handler : std::enable_shared_from_this<DerivedT>
{
  void some_method(arbitrary input) {
    do_something(shared_from_this());
  }
};

struct my_handler : shared_handler<my_handler>
{
  my_handler()
  {
    some_method("hello");
  }
};
template<class DerivedT>
struct shared_handler : std::enable_shared_from_this<shared_handler<DerivedT>>
{
  void some_method(arbitrary input) {
    do_something(shared_from_this());
  }
};

From cppreference :

It is permitted to call shared_from_this only on a previously shared object, ie on an object managed by std::shared_ptr<T> . Otherwise std::bad_weak_ptr is thrown (by the shared_ptr constructor from a default-constructed weak_this ).

Until C++17 it was undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM