Use std::enable_shared_from_this for this in smart pointer mode
As we all know that there is a this pointer for all objects, but if we want to use smart pointer, how to we use.
It turns out that it's not that easy by creating a share_ptr from this pointer, since we may have many shared_ptrs points to the same object with without knowing each other.
Taking this code as an example, if we create a share_ptr by dangerous function, we will have two share_ptrs pointing to the same object. Both sp1 and sp2 point to same object, and when the two exits it leads problem.
struct S
{
shared_ptr<S> dangerous() {
return shared_ptr<S>(this); // don't do this!
}
};
int main() {
shared_ptr<S> sp1(new S);
shared_ptr<S> sp2 = sp->dangerous();
return 0;
}
How to fix this problem, use the std::enable_shared_from_this help class defined in, it is introduced in C++11.
struct S: enable_shared_from_this<S> {
shared_ptr<S> dangerous() {
return shared_from_this();
}
};
int main() {
shared_ptr<S> sp1(new S);
shared_ptr<S> sp2 = sp->dangerous(); // not dangerous
return 0;
}