|
Boost : |
From: Joe Gottman (jgottman_at_[hidden])
Date: 2007-04-16 21:19:58
Peter Dimov wrote:
>
> To get back to shared_ptr, given p and q of type shared_ptr, would you be
> extremely disappointed if after:
>
> p = move( q );
>
> q holds the old value of p instead of being empty?
>
> (Note that p may have had a value that you could consider "unsafe" in the
> context of the valid values of q.)
>
Not extremely disappointed. I do think that move semantics would be
very useful for shared_ptr's, and I know that there are classes where it
would be prohibitively expensive to clear the source after a move
assignment. But note that it is possible to efficiently make q hold a
null pointer after a move assignment:
shared_ptr & operator=( shared_ptr && r ) // never throws
{
pn.swap(r.pn);
px = r.px;
r.px = 0;
return *this;
}
template <class Y>
shared_ptr &operator=(shared_ptr<Y> &&r) //never throws
{
pn.swap(r.pn);
px = r.px;
r.px = 0;
return *this;
}
This is actually fractionally more efficient than calling
swap(pn, r.pn); swap(px, r.px);
since swap(px, r.px) involves one copy constructor and two assignments
and the implementation I gave just involves two assignments. Also, in
the case of the template assignment operator it is not required that px
be convertible to Y*.
Joe Gottman
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk