C++中临时变量

</pre><p><span style="font-size:18px;"></span><pre name="code" class="cpp">
C++中临时对象的理解:

<span style="font-size:18px;">#include<iostream>

using namespace std;

class human
{
public:
	human()
	{
		human_num++; \
			cout << "this is default cosntructer!  " << "human num is " << human_num << endl;
	}
	human(const human &t)
	{
		cout << "this is copy constructer! human num is " << human_num << endl;;
	}
	static int human_num;
	~human()
	{
		human_num--;
		cout << "this is destructer,this = " << this << " ";
		print();
	}
	void print()
	{
		cout << "human num is " << human_num << endl;
	}
};

int human::human_num = 0;

human f1(human x)
{
	x.print();
   human t;
	return t;
}

int main()
{
	human h1;
	h1.print();
	human h2;
	h2 = f1(h1);
	h2.print();

	return 0;
}</span>
上述输出结果为:
this is default cosntructer!  human num is 1(定义h1产生)
human num is 1
this is default cosntructer!  human num is 2(定义h2产生)
this is copy constructer! human num is 2(在f1()函数中,执行了human x = h1语句产生)
human num is 2
this is default cosntructer!  human num is 3(定义局部变量t产生)
this is copy constructer! human num is 3(由于需要返回t,所以这里返回的实际是临时变量,执行human temp = t)
this is destructer,this = 0044FD97 human num is 2(临时变量temp析构)
this is destructer,this = 0044FDB8 human num is 1(局部变量t析构)
this is destructer,this = 0044FDE7 human num is 0(x析构)
human num is 0
this is destructer,this = 0044FEBF human num is -1(h2析构)
this is destructer,this = 0044FECB human num is -2(h1析构)

而对上述main函数做如下修改;

<span style="font-size:18px;">int main()
{
	human h1;
	h1.print();
	human h2 = f1(h1);
	h2.print();

	return 0;
}</span>

得到的结果为:
this is default cosntructer!  human num is 1(定义h1产生)
human num is 1
this is copy constructer! human num is 1(在f1()函数中,执行了human x = h1语句产生)
human num is 1
this is default cosntructer!  human num is 2
this is copy constructer! human num is 2(这里应该只是执行了human h2 = t的语句,而f1并没有将t返回到temp临时对象)
this is destructer,this = 0026FDDB human num is 1(局部变量t析构)
this is destructer,this = 0026FDFC human num is 0(x析构)
human num is 0
this is destructer,this = 0026FEF7 human num is -1(h2析构)
this is destructer,this = 0026FF03 human num is -2(h1析构)


由上可知,在C++中如果返回值是被构造函数调用,则不返回临时变量,如果返回值不是用于构造一个对象,则函数先返回一个
临时变量。上述结果是在vs2013_x64的机子上得到的结果,LZ用Dev-C++得到了不同的结果,在Dev-C++中运行第一个例子,函数f1
中明明有两个临时变量x和t但在函数执行完后只调用了一个析构函数。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值