Title
shared_ptr swap
Status
resolved
Section
[util.smartptr.shared.mod]
Submitter
Jonathan Wakely

Created on 2008-09-15.00:00:00 last changed 163 months ago

Messages

Date: 2010-11-20.00:05:46

Proposed resolution:

Recommend NAD EditorialResolved, fixed by N2844.

Date: 2010-11-20.00:05:46

[ Batavia (2009-05): ]

We agree with the proposed resolution. Move to NAD EditorialResolved.

Date: 2008-09-15.00:00:00
#include <memory>
#include <cassert>

struct A { };
struct B : A { };

int main()
{
    std::shared_ptr<A> pa(new A);
    std::shared_ptr<B> pb(new B);
    std::swap<A>(pa, pb);  // N.B. no argument deduction
    assert( pa.get() == pb.get() );
    return 0;
}

Is this behaviour correct (I believe it is) and if so, is it unavoidable, or not worth worrying about?

This calls the lvalue/rvalue swap overload for shared_ptr:

template<class T> void swap( shared_ptr<T> & a, shared_ptr<T> && b );

silently converting the second argument from shared_ptr<B> to shared_ptr<A> and binding the rvalue ref to the produced temporary.

This is not, in my opinion, a shared_ptr problem; it is a general issue with the rvalue swap overloads. Do we want to prevent this code from compiling? If so, how?

Perhaps we should limit rvalue args to swap to those types that would benefit from the "swap trick". Or, since we now have shrink_to_fit(), just eliminate the rvalue swap overloads altogether. The original motivation was:

vector<A> v = ...;
...
swap(v, vector<A>(v));

N1690.

History
Date User Action Args
2010-11-19 19:04:45adminsetstatus: nad editorial -> resolved
2010-10-21 18:28:33adminsetmessages: + msg4186
2010-10-21 18:28:33adminsetmessages: + msg4185
2008-09-15 00:00:00admincreate