0

In some usecases i want to use the unique_ptr as the function return, in order to transfer the ownership of function return to the function caller. Should i use unique_ptr as function return at all? If not, in which usecases should i use the unique_ptr as function return?

An example to explain my question detailedly:

unique_ptr<int> foo() {

  unique_ptr<int> rtn(0);

  *rtn = 10U;

  return std::move(rtn); // 1
  // return rtn; // 2
  // return rtn; // 3
}

void main() {
   unique_ptr<int> ptr = foo();// 1
   // unique_ptr<int> ptr = std::move(foo()); //2
   // unique_ptr<int> ptr = foo(); //3
}

In this example i just want to give the ownership of returned unique_ptr away from function foo() to caller. With the unique_ptr as function return, i want to tell the function caller, if you get the return value of this function, you must also take the responsibility to release it.

For this usecase should I use the unique_ptr at all? if yes, whcich variant from 1 to 3 should i use? If not, in which usecase should I use the unique_ptr as function return?

Jia Mu
  • 29
  • 1
  • 6
  • 1
    Returning `unique_ptr` is good. Writing through a null pointer is not. You don't need `std::move` at the call site, and the compiler will let you know if you need `std::move` in the return statement (since `unique_ptr` has no copy constructor to fall back to, it either moves successfully, elides the operation entirely, or errors) – Ben Voigt Feb 07 '20 at 22:30
  • What do you mean with "compiler let you know if you need std::move in the return statement"? If I don't use std::move on the function return value, actually will not receive compiler warnings. – Jia Mu Feb 08 '20 at 08:44
  • Your 2 & 3 variants in the first case and 1 & 3 variants in the second are identical. Am I missing something? – r3mus n0x Feb 08 '20 at 08:54
  • In variant 1: I move the unique_ptr in the function return, so that I don't need move it during the variable initilization. In variant 2: I move the unique_ptr during the variable initilization. In variant 3: I don't do anything in both parts. All of three variants should be able to compile. Mein question is only, which one is the correct one and why? – Jia Mu Feb 08 '20 at 17:43
  • 1
    "If I don't use std::move on the function return value, actually will not receive compiler warnings." That's because the C++ rules make this an *xvalue* ("expiring" because it is going out of scope) and therefore the compiler will move it without you having to ask. All three variants compile, and all three do exactly the same thing. Leaving off the `std::move` is best because it's easier to read and easier for the compiler to do NRVO. – Ben Voigt Feb 09 '20 at 20:58

0 Answers0