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 bystd::shared_ptr<T>
. Otherwisestd::bad_weak_ptr
is thrown (by theshared_ptr
constructor from a default-constructedweak_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.