c++ - Returning unique_ptr from functions -
unique_ptr<t>
not allow copy construction, instead supports move semantics. yet, can return unique_ptr<t>
function , assign returned value 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 , works intended. how line 1
doesn't invoke copy constructor , result in compiler errors? if had use line 2
instead it'd make sense (using line 2
works well, we're not required so).
i know c++0x allows exception unique_ptr
since return value temporary object destroyed function exits, guaranteeing uniqueness of returned pointer. i'm curious how implemented, special cased in compiler or there other clause in language specification exploits?
is there other clause in language specification exploits?
yes, see 12.8 §34 , §35:
when criteria met, implementation allowed omit copy/move construction of class object [...] elision of copy/move operations, called copy elision, permitted [...] in return statement in function class return type, when expression name of non-volatile automatic object same cv-unqualified type function return type [...]
when criteria elision of copy operation met , object copied designated lvalue, overload resolution select constructor copy first performed as if object designated rvalue.
just wanted add 1 more point returning value should default choice here because named value in return statement in worst case, i.e. without elisions in c++11, c++14 , c++17 treated rvalue. example following function compiles -fno-elide-constructors
flag
std::unique_ptr<int> get_unique() { auto ptr = std::unique_ptr<int>{new int{2}}; // <- 1 return ptr; // <- 2, moved returned unique_ptr } ... auto int_uptr = get_unique(); // <- 3
with flag set on compilation there 2 moves (1 , 2) happening in function , 1 move later on (3).
Comments
Post a Comment