enable_shared_from_this creates a shared_ptr from an empty weak ptr. This makes no sense to me - I would have thought that the weak ptr should be initialized with this instead; that makes sense...
So how does this class create a shared_ptr from this if it bases the shared_ptr on an empty weak_ptr?
Am I clear?
My guess is that this empty weak_ptr is exacly what makes it work, but why?
enable_shared_from_this effectively has a mutable weak_ptr as a member sub-object. The weak_ptr is initially empty, but it doesn't usually stay that way.
x.shared_from_this() requires that a shared_ptr to x exists before it is called. The requirement is necessary because the weak_ptr is set up by the shared_ptr constructor. It is this first shared_ptr that allocates the control structures.
For example
1 2 3 4 5 6 7 8
#include <memory>
struct A : std::enable_shared_from_this<A> {};
int main()
{
auto pa = new A;
auto s1 = std::shared_ptr<A>(pa);
auto s2 = pa->shared_from_this();
}
After line 6 *pa's internal weak_ptr is no longer empty.
Without line 6 line 7 would throw bad_weak_ptr.
> how does line 6 of @mbozzi code set the internal _Wptr to own this (A)?
The shared pointer is a friend. lines 37, 38: template < class Y > friendclass shared_ptr;
The constructor of the shared pointer, given a pointer U*
determines if U has an unambiguous and accessible base class that is a specialization of std::enable_shared_from_this, and if so, the constructor evaluates the statement:
1 2 3
if (ptr != nullptr && ptr->weak_this.expired())
ptr->weak_this = std::shared_ptr<std::remove_cv_t<U>>(*this,
const_cast<std::remove_cv_t<U>*>(ptr));