softineer
softineer

Reputation: 13

unique_ptr without move, why is this working?

During a code review I found that a C++ function expecting a unique_ptr gets passed the uniqe_ptr by std::move but neither does the function move the unique_ptr as return value nor assigns the caller the return unique_ptr back to it's unique_ptr, so I'd expect this would crash.

Example:

   std::unique_ptr<X> fun(std::unique_ptr<X> p) {
     // Do something with the unique_ptr p
     return p;
   }

At some other place, I found the following calls:

void someFunction() {
  auto p = std::make_unique<X>();
  //...
  fun(std::move(p));
  // Do something else
  fun(std::move(p));
  //...
}

So I'm wondering whether this code is OK or if it is just luck that it executes.

[EDIT]: Completed the example

Upvotes: 1

Views: 342

Answers (2)

Ferruccio
Ferruccio

Reputation: 100748

It looks to me like the intent was to call fun like this:

p = fun(std::move(p));
p = fun(std::move(p));

In which case ownership of p would be passed back-and-forth to and from the function. I would have preferred to make fun a void function and pass p in by reference or even as a raw X* type.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249592

In this fragment:

fun(std::move(p));
fun(std::move(p));

p is moved-from, which leaves it null. So the second time you call fun(), it receives a null pointer. Which is fine, so long as it does not dereference that pointer.

Upvotes: 2

Related Questions