Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2004-02-13 13:39:48


On Feb 12, 2004, at 8:34 AM, Peter Dimov wrote:

> The reason for this restriction is that enable_shared_from_this<foo>
> contains a weak_ptr<foo>, and in order to initialize it from a
> shared_ptr
> that stores a pointer to const foo, the implementation would need to
> const_cast the constness away twice, once in order to access the
> weak_ptr
> member, a second time to initialize a weak_ptr<foo> from a
> shared_ptr<foo
> const>.

I'm having trouble finding a case where this suggestion produces
undesirable results. If deriving from enable_shared_from_this<const
foo>, everything seems to work, except that you can not:

shared_ptr<foo> sp2(sp->shared_from_this());

where sp was created with:

shared_ptr<foo> sp(ap);

and ap is:

auto_ptr<foo> ap(new foo);

which seems very reasonable to me. If foo instead derives from
enable_shared_from_this<foo>, then I can find no questionable behavior
for:

typedef [const] foo F1;
typedef [const] foo F2;
typedef [const] foo F3;

auto_ptr<F1> ap(new foo);
shared_ptr<F2> sp(ap);
shared_ptr<F3> sp2(sp->shared_from_this());

for all combinations of const and non-const. Your const_cast
suggestion appears to work when it is supposed to, and fail (at compile
time) when it is supposed to, at least on the Metrowerks implementation
of std::tr1::shared_ptr. If you see a suspicious test that you would
like me to try on this modified and experimental implementation, I'd be
happy to report back.

-Howard


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