Boost logo

Boost :

From: Sebastian Redl (sebastian.redl_at_[hidden])
Date: 2005-12-07 10:57:35


Yuval Ronen wrote:

>Hi.
>There's a shared_ptr constructor that accepts an auto_ptr<Y>&. Shouldn't
>it accept auto_ptr<Y> by value rather by non-const reference? It seems
>to me that the reference does not add anything, but only causes a VC
>warning (level 4):
>
>---
>warning C4239: nonstandard extension used : 'argument' : conversion from
>'std::auto_ptr<_Ty>' to 'std::auto_ptr<_Ty> &'
>A reference that is not to 'const' cannot be bound to a non-lvalue
>---
>
>when calling this constructor with a temporary auto_ptr.
>This warning is a good thing and I don't want to disable it.
>
>Thanks,
>Yuval
>
>
Don't call the constructor with a temporary.

Anyway, there's a good reason for this: the semantics of auto_ptr.
auto_ptr works with transfer of ownership: there can only be one
auto_ptr at any time holding a specific pointer. When you assign or
copy-construct auto_ptrs, ownership is transferred: the old pointer is
set to NULL.
Due to this, the auto_ptr will always destruct its pointee when it gets
destructed. auto_ptr does not care about shared_ptr's reference count.
To have shared_ptr not point to deleted memory, constructing a
shared_ptr from an auto_ptr must prevent auto_ptr from deleting the
pointee. And the only way to do that is to set it to NULL. This is why
it needs to be passed as non-const reference; otherwise you couldn't
modify it.
Note that auto_ptr's own copy constructor and assignment operator also
take non-const references. So even if you made shared_ptr's constructor
take an auto_ptr by value, you'd still get the warning, this time from
auto_ptr's constructor. Only this time you'd have an additional, useless
temporary.

Sebastian Redl


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