编译器 gcc 4.5.3 (cygwin)
我试图确定在什么条件下为参数调用复制构造函数,并且我想找到一种传递不需要调用复制构造函数的参数的方法。我构建了以下测试代码来探索这个问题。
在下面的代码中,复制构造函数为 fnc1() 调用了两次。有什么理由应该多次调用它?
有没有办法不调用复制构造函数?
# include <iostream>
using namespace std;
class able {
public:
long x;
able(): x(1) {}
able(const able&) {cout << " const "; }
~able() { cout << " ~able" << endl; }
};
able fnc1(able x) { cout << "fnc1(able x)" ; return x; }
able fnc2(able& x) { cout << "fnc2(able& x)" ; return x; }
able fnc3(const able& x) { cout << "fnc3(const able& x)" ; return x; }
able fnc4(able const & x) { cout << "fnc4(able const & x)" ; return x; }
able fnc5(able* x) { cout << "fnc4(able* x)" ; return *x; }
int main(int argc, char** argv) {
able* x = new able();
fnc1(*x);
fnc2(*x);
fnc3(*x);
fnc4(*x);
fnc5(x);
cout << "test fini" << endl;
return 0;
}
output
const fnc1(able x) const ~able
| | |
| | o first destrucor
| |
| o second call
o first call
~able
|
o second destructor
fnc2(able& x) const ~able
fnc3(const able& x) const ~able
fnc4(able const & x) const ~able
fnc4(able* x) const ~able
test fini