Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2005-01-12 17:14:59


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

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk