Re: rvalues and lvalues
On Dec 9, 6:56 am, Frank Birbacher wrote:
[...]
Ok, I guess today I have successfully used this technique to correctly
return a unique_ptr member variable from a member function.
If you want to be sure about it, post an example. ;-)
I'm responding because I'd like to stress that std::move should only
be used when necessary because in some cases it's actually a bit
counter productive. Example:
unique_ptr<int> source() {
unique_ptr<int> p (new int(42));
return std::move(p);
}
Here, the std::move call is not needed. Even though, p is an lvalue
expression, the compiler knows that it refers to a local object which
is about to be destroyed right on exiting the function. So, in this
case, the compiler will automatically consider a move construction.
There is something even better than a move construction: a copy/move
elision (more specifically in this case: NRVO = named return value
optimization). The use of std::move actually inhibits this
optimization. So, prefer to write
unique_ptr<int> source() {
unique_ptr<int> p (new int(42));
return p;
}
instead (without std::move). :-)
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]