The enable_shared_from_this
helper contains a weak pointer that is set when creating shared pointer to the object. That means there is the reference-count (allocated separately or together with the object using make_shared
) and an extra weak_ptr
in the object.
Now why doesn't it simply contain the reference count instead? When setting shared_ptr
from dumb pointer, the type has to be fully defined, so the shared_ptr
constructor or assignment operator can detect the type is derived from enable_shared_from_this
and use the correct counter and the format can remain the same, so copying does not care. In fact, the shared_ptr
already has to detect it to set the embedded weak_ptr
.
The first thing that comes to mind is whether that approach would be feasible at all, and the answer is that it would not:
struct X : enable_shared_from_this {};
std::shared_ptr<X> p( new X );
std::weak_ptr<X> w( p );
p.reset(); // this deletes the object
if ( w.use_count() ) { // this needs access to the count object
// but it is gone! Undefined Behavior
If the count is stored in the object, then no weak_ptr
can outlive the object, which is a breach in the contract. The whole idea of weak_ptr
is that they can outlive the object (if the last shared_ptr
goes out of scope, the object is deleted even if there are weak_ptr
)