lundi 28 mai 2018

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

Aucun commentaire:

Enregistrer un commentaire