class widget {
public:
widget(){ std::cout << "default construct called." << std::endl;}
widget(const widget& rhs){ std::cout << "copy construtor called." << std::endl;}
widget& operator=(const widget& rhs) { std::cout << "assign constructor called." << std::endl;}
};
widget& func_ret_ref()
{
widget w;
return w;
}
widget func_ret_val()
{
widget w;
return w;
}
int main()
{
widget x = func_ret_val();
std::cout << ".................." << std::endl;
widget y = func_ret_ref();
}
在没有关闭返回值优化的情况下,输出为:
default construct called.
..................
default construct called.
copy construtor called.
关闭返回值优化时,输出为:
default construct called.
copy construtor called.
copy construtor called.
..................
default construct called.
copy construtor called.
返回值优化时,如果是返回类对象的值,会直接将构造函数应用于widget x;因此只调用一次默认构造函数。
关闭返回值优化时,如果是返回类对象的值,则针对widget x = func_ret_val(); 首先函数func_ret_val()会生成一个临时对象,因此会调用一次copy constructor。然后生成x的时候,使用该临时对象,又会调用一次copy constructor。
返回类对象引用时,并不会生成该临时对象,所以少了一次copy constructor的调用。