コンパイラgcc4.5.3(cygwin)
コピーコンストラクターが引数に対して呼び出される条件を特定しようとしています。コピーコンストラクターを呼び出す必要のない引数を渡す方法を見つけたいと思います。この問題を調査するために、次のテストコードを作成しました。
次のコードでは、コピーコンストラクターがfnc1()に対して2回呼び出されます。複数回呼び出す必要がある理由は何ですか?
コピーコンストラクターを呼び出さない方法はありますか?
# 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