Quick Q: Why can I return a unique_ptr by value? -- StackOverflow

Quick A: Because return local_obj; automatically treats it as an rvalue. After all, you won't be using it any more.

When this FAQ came up again recently on SO, the answer was to refer to this previous Q&A:

Returning unique_ptr from functions

unique_ptr<T> does not allow copy construction, instead it supports move semantics. Yet, I can return a unique_ptr<T> from a function and assign the returned value to a variable...

unique_ptr<int> foo()
{
  unique_ptr<int> p( new int(10) );

  return p;                   // 1
  //return move( p );         // 2
}

The code above compiles and works as intended. So how is it that line 1 doesn't invoke the copy constructor and result in compiler errors? If I had to use line 2 instead it'd make sense (using line 2 works as well, but we're not required to do so)....

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.