如果函数通过pass by value方式返回结果,一定用到copy constructor吗?
D100 2004-05-07 04:21:17 是从某个帖子所想到的
http://expert.csdn.net/Expert/topic/3038/3038725.xml?temp=.7782251
下面有一个简单的例子,在devc++上编译
#include <iostream>
using namespace std;
class A
{
public:
A() {cout << "call ctor" << endl;}
A(const A&) { cout << "call copy ctor" << endl;}
A& operator= (const A&) { cout << "call assignment" << endl;}
~A() {cout << "call dtor" << endl;}
};
A test()
{
A tmp;
return tmp;
}
int main()
{
{
A a;
a = test();
}
system("PAUSE");
}
输出结果是:
call ctor
call ctor
call copy assignment
call dtor
call dtor
并没有调用到copy constructor,是编译器优化的结果吗?nrv或类似的东东?
但nvr优化需要先定义一个copy ctor才能实施吗?