Nick
Nick

Reputation: 3435

How to move ownership across unique_ptrs

I have two smart-pointers:

Foo *p1 = new Foo;
Foo *p2 = new Foo;
std::unique_ptr<Foo> u1(p1);
std::unique_ptr<Foo> u2(p2);

Now I want u1 to own p2. And I want u2 to own nothing (or nullptr). Of cource, at the same time p1 must be deleted gracefully.

What C++ code should I write to accomplish it?

Upvotes: 3

Views: 622

Answers (3)

Chris Drew
Chris Drew

Reputation: 15334

Use std::move to cast u2 to an rvalue then use move assignment to "move" u2 into u1:

u1 = std::move(u2);

After the move, u2 will be nullptr although that is special case for unique_ptr, don't expect moved from objects to be in any particular state generally. And of course p1 will be deleted gracefully.

I recommend you don't create p1 or p2 at all and never have any owning raw pointers:

std::unique_ptr<Foo> u1(new Foo);

Or better yet, in C++14:

auto u1 = std::make_unique<Foo>();

Upvotes: 6

Marco A.
Marco A.

Reputation: 43662

The two versions below will do the same thing:

u1 = std::move(u2);

and

u1.swap(u2);
u2.reset(nullptr);

although the first is more efficient. u2 will hold a nullptr in both cases.

I'm also joining the chorus for using std::make_unique in C++14 (more efficient and in many cases, safer).

Upvotes: 3

T.C.
T.C.

Reputation: 137310

What you want to do is basically the description of move assignment for unique_ptr, modulo the deleter part (not relevant here):

u1 = std::move(u2);

Upvotes: 4

Related Questions