I see no reason why it would be technically impossible to get a pointer here, since the shared pointer object obviously still exists and can be used.
There is a very good technical reason why this is not possible.
shared_ptr may exist, but the reference count for object A reached zero, so the destructor starts. When the reference counter reaches zero, it cannot be incremented again (otherwise you can get shared_ptr , which refers to an object that is either in the middle of its destructor launch, or has already been destroyed).
The call to shared_from_this() tries to increase the reference counter and returns a shared_ptr , which shares ownership with the current owner (s), but you cannot increase the counter from zero to one, so it does not work.
In this very specific case (inside the object’s destructor), you know that the object has not yet been completely destroyed, but enable_shared_from_this<A> has no way of knowing who is calling the shared_from_this() function, so you cannot know if this is happening in this particular case or in some other piece of code outside the destructor object (for example, in another thread that will continue after the destructor).
If you could somehow make it work in this particular case, and you got shared_ptr<A> that referred to the object being destroyed, you could give this shared_ptr something outside the destructor that saved it for later use. This would allow another piece of code to access the tattered shared_ptr after the destruction of the object. This will be a big hole in a system like shared_ptr and weak_ptr .
Jonathan wakely
source share