Quick Q: A unique_ptr is not copyable, so why can I return one by value? -- StackOverflow

 

A common question for programmers new to C++11 and its new features: "Hey, look how easy this was! ... But, um, why and how did it work?"

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.

#include <iostream>
#include <memory>
using namespace std;

unique_ptr<int> foo()
{
  unique_ptr<int> p( new int(10) );
  return p;                   // 1
  //return move( p );         // 2
}

int main()
{
  unique_ptr<int> p = foo();
  cout << *p << endl;
  return 0;
}

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).

I know C++0x allows this exception to unique_ptr since the return value is a temporary object that will be destroyed as soon as the function exits, thus guaranteeing the uniqueness of the returned pointer. I'm curious about how this is implemented, is it special cased in the compiler or is there some other clause in the language specification that this exploits?

Continue reading...

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.