下面的例子分别用Visual Studio 2012中的编译器(默认和O2优化结果不一样哦)和G++4.7.2(mingw)结果。
代码如下 |
复制代码 |
#include
using namespace std;
class A
{
public:
int a;
A(int i):a(i)
{
cout << "A() :" << a << endl;
}
~A()
{
cout << "~A()" << a << endl;
}
A(const A& x):a(x.a)
{
cout << "copy A()" << a << endl;
}
};
A test1()
{
return A(1);
}
A test2()
{
A tmp(2);
return tmp;
}
int main()
{
A a = test1();
A b = test2();
cout << "before exit" << endl;
return 0;
}
|

可以看出,编译器面对这样的情况都做了相关的优化,VS2012自带的编译器默认情况下才能看到copy 构造函数的调用。