一句话,直接返回即可,不用任何变化。
当启动了c++11选项后,通过函数返回代码没有发生任何变化,但是已经使用了move语义,而不需要之前的NRVO编译器优化技术。
注意,右值引用rvalue reference是表达式计算完成后就不再存在的临时变量,左值是表达式计算完成后的变量。如果能够用&求址的,就是左值。
?
下面是stackoverflow上的一个讨论贴,比较有价值:
?
| 246down voteaccepted | 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.
|
||||||||||||||||||||||||||||||
| ? |
|