Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2004-02-13 16:14:47

Howard Hinnant wrote:
> 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.

I'm slowly reaching the same conclusion.


> 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.

One interesting case that is missing from your example is "new F1", when F1
is const foo. The auto_ptr is a distraction:

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

As Joe Gottman correctly pointed out, the weak_ptr<foo> in
enable_shared_from_this<foo> needs to be mutable, since it can be part of a
genuine const object.

That aside, I think I almost convinced myself that the second const_cast
(initializing weak_ptr<foo> from a foo const*) is safe, since the two
shared_from_this() overloads take care of the const correctness.

    foo * p = new foo;
    shared_ptr<foo const> sp( (foo const*)p );

is still fine.

Boost list run by bdawes at, gregod at, cpdaniel at, john at