问题
Possible Duplicate:
Returning unique_ptr from functions
20.7.1.2 [unique.ptr.single] defines copy constructor like this :
// disable copy from lvalue
unique_ptr(const unique_ptr&) = delete;
unique_ptr& operator=(const unique_ptr&) = delete;
So, why the following code compiles fine?
#include <memory>
#include <iostream>
std::unique_ptr< int > bar()
{
std::unique_ptr< int > p( new int(4));
return p;
}
int main()
{
auto p = bar();
std::cout<<*p<<std::endl;
}
I compiled it like this :
g++ -O3 -Wall -Wextra -pedantic -std=c++0x kel.cpp
The compiler : g++ version 4.6.1 20110908 (Red Hat 4.6.1-9)
回答1:
In the return statement, if you return a local variable, the expression is treated as an rvalue, and thus automatically moved. It is thus similar to:
return std::move(p);
It invokes the unique_ptr(unique_ptr&&)
constructor.
In the main function, bar()
produces a temporary, which is an rvalue, and is also properly moved into the p
in main
.
回答2:
It is not copied, it is moved.
The return statement is equivalent to this:
return std::move(p);
Pedantically speaking, that is semantically equivalent. In reality, the compiler may optimize the code, eliding the call to the move-constructor. But that is possible only if you write it as:
return p; //It gives the compiler an opportunity to optimize this.
That is recommended. However, the compiler has no opportunity to optimize if you write this:
return std::move(p); //No (or less) opportunity to optimize this.
That is not recommended. :-)
回答3:
I think that copying from an lvalue is disabled, but "bar()" is an rvalue so it's OK. You definitely need to be able to copy from rvalues.
来源:https://stackoverflow.com/questions/9827183/why-am-i-allowed-to-copy-unique-ptr