分析一下代码,调用GetA()之后,在函数内会生成一个临时对象,调用一次构造函数,然后将此临时对象拷贝给函数的返回值,调用一次拷贝构造函数,此返回值也是一个临时对象,返回值再拷贝给a对象,调用一次拷贝构造函数。
总的来说,生成了3个对象,其中有2个是临时对象。
#include <iostream>
using namespace std;
int constructcount=0;
int copycount=0;
int destructcount=0;
struct A
{
A(){
cout<<"construct: "<<++constructcount<<endl;
}
A(const A& a){
cout<<"copy construct: "<<++copycount<<endl;
}
~A(){
cout<<"destruct: "<<++destructcount<<endl;
}
};
A GetA()
{
return A();
}
int main() {
A a = GetA();
return 0;
}
运行结果如下:
-fno-elide-construct