c++11 函数内部返回对象使用move语义的最佳实践
一句话,直接返回即可,不用任何变化。
当启动了c++11选项后,通过函数返回代码没有发生任何变化,但是已经使用了move语义,而不需要之前的NRVO编译器优化技术。
注意,右值引用rvalue reference是表达式计算完成后就不再存在的临时变量,左值是表达式计算完成后的变量。如果能够用&求址的,就是左值。
下面是stackoverflow上的一个讨论贴,比较有价值:
First example
The first example returns a temporary which is caught by
except that in my rewrite you obviously can‘t use rval_ref in a non-const manner. Second example
In the second example you have created a run time error. rval_ref now holds a reference to the destructed tmp inside the function. With any luck, this code would immediately crash. Third example
Your third example is roughly equivalent to your first. The std::move on tmp is unnecessary and can actually be a performance pessimization as it will inhibit return value optimization. The best way to code what you‘re doing is: Best practice
I.e. just as you would in C++03. tmp is implicitly treated as an rvalue in the return statement. It will either be returned via return-value-optimization (no copy, no move), or if the compiler decides it can not perform RVO, then it will use vector‘s move constructor to do the return. Only if RVO is not performed, and if the returned type did not have a move constructor would the copy constructor be used for the return. | |||
我在前几天的程序中当用这种情况的时候返回vector<string>,遇到了core dump,换成了vector<string> & output参数的方式得以解决。还需要进一步追踪,是否是clang++ 3.5的bug。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。
return my_local;
. Multiple return statements are ok and will not inhibit RVO. – Howard Hinnant Feb 25 ‘13 at 20:18move
doesn‘t create a temporary. It casts an lvalue to an xvalue, making no copies, creating nothing, destroying nothing. That example is the exact same situation as if you returned by lvalue-reference and removed themove
from the return line: Either way you‘ve got a dangling reference to a local variable inside the function and which has been destructed. – Howard Hinnant Feb 27 ‘13 at 16:11tmp
) in the "Best practice" section, it is the NRVO that kicks in, not the RVO. These are two different optimizations. Other than that, great answer! – Daniel Frey Feb