c++中的值传递

大家都知道,在c++中,值传递的时候在栈里面会创建一个临时的对象,那么它会不会调用对应的构造函数和析构函数呢?猜想的话,应该是会调用了的...额,可是做了一个测试...从现象中发现只调用了...析构函数,那么到底有没有调用构造函数呢...

#include<iostream>
using namespace std;

class B{
int i;
public:
B()
{
	i = 0;
	cout<<"construct b..."<<endl;
}
~B()
{
	cout<<"destruct b..."<<endl;
}

};

void fun1(B b)
{
	;
}

int main()
{

	int j;
	B b;	

	fun1(b);
	fun1(b);
	j = 0;
	return 0;
}


额,后来发现其是由一个已经存在的对象创建一个新的对象,做一下修改:

#include<iostream>
using namespace std;

class B{
int i;
public:
B()
{
	i = 0;
	cout<<"construct b..."<<endl;
}
B(const B &b)
{
	i = 0;
	cout<<"default copy construct b..."<<endl;
}
~B()
{
	cout<<"destruct b..."<<endl;
}

};

void fun1(B b)
{
	;
}

int main()
{

	int j;
	B b;	

	fun1(b);
	fun1(b);
	j = 0;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值