shared_from_this
can be used to obtain a shared_ptr
from an object that is already managed by a shared_ptr
.
Calling shared_from_this
on a non-shared object is undefined behavior in C++11.
However, in C++17 shared_from_this
will throw bad_weak_ptr
and you can catch this exception:
#include <memory>
#include <iostream>
class X : public std::enable_shared_from_this<X> {
public:
bool is_shared() const {
try {
shared_from_this();
return true;
} catch (std::bad_weak_ptr&) {
return false;
}
}
};
int main() {
X x;
std::cout << std::boolalpha << x.is_shared() << std::endl;
auto y = std::make_shared<X>();
std::cout << y->is_shared() << std::endl;
}
Output:
false
true
Furthermore you can use weak_from_this
to get access to weak_ptr
's expired
method:
bool is_shared() const {
return !weak_from_this().expired();
}
shared_from_this
to ever returnnullptr
in a well defined program. – François Andrieux May 2 '18 at 13:19