关于构造函数和析构函数的隐式调用

一、首先是最基本的调用:

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


结论:当将对象传递给函数或从函数返回该类型对象时,将隐式使用复制构造函数。与每一个复制构造函数都有一个对应的析构函数。




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值