一、首先是最基本的调用:
class Test
{
public:
Test() {cout<<"default constructor"<<endl;}
~Test() {cout<<"default destructor"<<endl;}
Test(int i):a(i){cout<<"from copy"<<endl;}
Test(const Test&) {cout<<"copy constructor"<<endl;}
private:
int a;
};
int main() {
Test t;
}
输出结果如下:
default constructor
default destructor
二、在形参值传递时的调用:
class Test
{
public:
Test() {cout<<"default constructor"<<endl;}
~Test() {cout<<"default destructor"<<endl;}
Test(int i):a(i){cout<<"from copy"<<endl;}
Test(const Test&) {cout<<"copy constructor"<<endl;}
private:
int a;
};
void play(Test b)
{
}
int main() {
Test a;
cout<<"********"<<endl;
play(a);
return 0;
}
结果:
default constructor
********
copy constructor
default destructor
default destructor
说明:将对象传递给函数时,将隐式调用复制构造函数。而这个创建的对象会在函数结束后销毁。
三、在用值来返回时的调用:
class Test
{
public:
Test() {cout<<"default constructor"<<this<<endl;}
~Test() {cout<<"default destructor"<<this<<endl;}
Test(int i):a(i){cout<<"from copy"<<endl;}
Test(const Test&) {cout<<"copy constructor"<<this<<endl;}
private:
int a;
};
Test play(Test b)
{
return b;
}
int main() {
Test a;
cout<<"********"<<endl;
play(a);
return 0;
}
结果:
default constructor0x28ff04
********
copy constructor0x28ff0c
copy constructor0x28ff08
default destructor0x28ff08
default destructor0x28ff0c
default destructor0x28ff04
说明:从函数返回对象时,会隐式调用复制构造函数,以及对应的析构函数。
四、隐式转化调用构造函数
class Test
{
public:
Test() {cout<<"default constructor"<<this<<endl;}
~Test() {cout<<"default destructor"<<this<<endl;}
Test(int i):a(i){cout<<"from copy"<<endl;}
Test(const Test&) {cout<<"copy constructor"<<this<<endl;}
private:
int a;
};
void play(Test b)
{
//return b;
}
int main() {
play(1);
结果:
from copy
default destructor0x28ff0c
五、隐式转换和隐式调用复制构造函数
class Test
{
public:
Test() {cout<<"default constructor"<<this<<endl;}
~Test() {cout<<"default destructor"<<this<<endl;}
Test(int i):a(i){cout<<"from copy"<<endl;}
Test(const Test&) {cout<<"copy constructor"<<this<<endl;}
private:
int a;
};
Test play(Test b)
{
return b;
}
int main() {
play(1);
return 0;
}
结果:
from copy
copy constructor0x28ff08
default destructor0x28ff08
default destructor0x28ff0c
结论:当将对象传递给函数或从函数返回该类型对象时,将隐式使用复制构造函数。与每一个复制构造函数都有一个对应的析构函数。