shared_ptr to self while in constructor

Hello all, A direct call to shared_from_this() does not work in a constructor. Is there any way that I may obtain a shared_ptr to myself while under construction? Thanks, Dave

On Wed, Jan 12, 2005 at 09:11:43AM -0700, Dave wrote:
A direct call to shared_from_this() does not work in a constructor. Is there any way that I may obtain a shared_ptr to myself while under construction?
I don't think so - since shared_from_this() requires the object to already be owned by another shared_ptr, which can't be possible if the object hasn't been constructed yet. When you create a shared_ptr from a raw pointer, shared_ptr's constructor checks whether the pointee is of a type derived from enable_shared_from_this and if so it initialises a weak_count in the enable_shared_from_this base class. Since you have not constructed your object yet you cannot have passed its address to a shared_ptr yet, so the weak_count can't have been initialised, so shared_from _this() will throw a bad_weak_ptr. jon -- "Everything is permitted." - Fyodor Dostoyevsky, 'The Brothers Karamazov'

Jonathan Wakely wrote:
On Wed, Jan 12, 2005 at 09:11:43AM -0700, Dave wrote:
A direct call to shared_from_this() does not work in a constructor. Is there any way that I may obtain a shared_ptr to myself while under construction?
I don't think so - since shared_from_this() requires the object to already be owned by another shared_ptr, which can't be possible if the object hasn't been constructed yet.
When you create a shared_ptr from a raw pointer, shared_ptr's constructor checks whether the pointee is of a type derived from enable_shared_from_this and if so it initialises a weak_count in the enable_shared_from_this base class.
Since you have not constructed your object yet you cannot have passed its address to a shared_ptr yet, so the weak_count can't have been initialised, so shared_from _this() will throw a bad_weak_ptr.
Can't you just go back to the old practice of deriving your class from shared_count? -- Dave Abrahams Boost Consulting http://www.boost-consulting.com

Dave wrote:
Hello all,
A direct call to shared_from_this() does not work in a constructor. Is there any way that I may obtain a shared_ptr to myself while under construction?
In short, no. You don't know which deleter to use. But can't you use a static create function as explained here: http://boost.org/libs/smart_ptr/sp_techniques.html#in_constructor
participants (4)
-
Dave
-
David Abrahams
-
Jonathan Wakely
-
Peter Dimov