#include <string>
std::string f(bool cond = false) {
std::string first("first");
std::string second("second");
// the function may return one of two named objects
// depending on its argument. RVO might not be applied
return cond ? first : second;
}
int main() {
std::string result = f();
}
其实问题不在于编译器能否使用返回值优化(RVO),而是它是否能避免进行复制构造。
请看:
struct Blah
{
int x;
Blah( int const _x ): x( _x ) { cout << "Hum de dum " << x << endl; }
};
Blah foo()
{
Blah const a( 1 );
if( fermatWasRight() ) { return Blah( 2 ); }
return a;
}
a
不太兼容。但是如果编译器足够聪明,则它可以注意到销毁此对象是一个空操作。并且更普遍地说,对于任何特定情况,如果编译器足够聪明,则即使我们如何狡猾地设计代码,它也可能设法避免复制操作。