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?
unique_ptr
. The whole question is about 1 and 2 being two different ways of achieving the same thing. – Whirlwindmain
function exits , but not when thefoo
exits. – Enkindle