I'm using enable_shared_from_this<Base> and then inherit from Base. When trying to use shared_from_this() in Derived's constructor (not initializer list), I get an exception. Turns out that the internal weak pointer is null and doesn't point to this at all. How can this happen? My other use case of exactly this works perfectly fine. I don't even know where to start. I looked down at the source code of enable_shared_from_this, and it looks to me like that pointer would always be nullptr.
-
1Not really a duplicate: http://stackoverflow.com/questions/4428023/enable-shared-from-this-c0x-what-am-i-doing-wrong – CB Bailey Dec 20 '10 at 23:07
3 Answers
You cannot call shared_from_this() in the object's constructor. shared_from_this() requires that the object is owned by at least one shared_ptr. An object cannot be owned by a shared_ptr before it is constructed.
I would guess that the internal weak pointer is set when a shared_ptr takes ownership of the object for the first time. Before that point, there is no reference count struct that the weak pointer can reference.
- 348,265
- 75
- 913
- 977
James McNellis's answer is right.
As for the explanation of the enable_shared_from_this template itself, which as you observe appears to do nothing, note 7 at the bottom of this page explains:
...the template
enable_shared_from_thisholds aweak_ptrobject that points to the derived object. There's a chicken-and-egg problem, though, about how to initialize thatweak_ptrobject when there is no correspondingshared_ptrobject. The implementation trick is that the constructors forshared_ptrknow aboutenable_shared_from_this, and set theweak_ptrobject during construction of ashared_ptrobject that owns a resource that hasenable_shared_from_thisas a public base class.
- 1
- 1
- 50,331
- 10
- 105
- 169
Conceptually, shared_from_this() picks a shared_ptr pointing to this and returns a copy of it.
In the constructor, there is no shared_ptr pointing to this.
- 8,038
- 2
- 40
- 58