【发布时间】:2013-06-18 01:50:52
【问题描述】:
我了解了防止临时对象生成的返回值优化(Object return in C++、http://en.wikipedia.org/wiki/Return_value_optimization、http://blog.knatten.org/2011/08/26/dont-be-afraid-of-returning-by-value-know-the-return-value-optimization/)。
我还了解了右值引用 (http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html),它也可用于防止临时对象生成。
实际上,我可以只返回值而不用担心复制对象的性能下降吗?
我的意思是,这两个代码 sn-p 等效吗?
A hello()
{
A a(20);
cout << &a << endl;
return a;
}
// rvalue reference to prevent temporary object creation
A&& a = hello();
cout << &a << endl;
// expects compiler remove the temporary object
A a = hello();
cout << &a << endl;
【问题讨论】:
-
C++11 rvalues and move semantics confusion 的可能副本。另请阅读this。
-
A&& a = hello();-- 不要那样做。 -
这link 有帮助吗?
-
@Benjamin Lindley:你能解释一下为什么不推荐 A&& a = hello() 吗?
标签: c++ return-value rvalue-reference