空闲时候思考之C++的临时量

#include<iostream>
using namespace std;


class x
{
public:
	x(int ii=0);
	void modify();
	x f8();
	~x();
	x& operator=(const x &x1);
private:
	int i;
};


x::x(int ii/* =0 */):i(ii)
{
cout<<"x():  "<<this<<endl;
}
x::~x()
{
	cout<<"~x() :"<<this<<endl;
}
x& x::operator=(const x &x1)
{
	cout<<"=(): "<<this<<endl;
	if(&x1 != this)
	{
      i = x1.i;
	}
	return *this;
}
void x::modify()
{
	cout<<"Modify:  "<<this<<endl;
	i++;
}

x f5()
{
	return x();
}
const x f6()
{
	return x();//返回一个无名的临时变量,临时量就会变成常量
}

void f7( x &xx)
{
	xx.modify();
}
x x::f8()
{
	cout<<"f8() :"<<this<<endl;
	return x();
}


void main()
{
	x a(1);
	f5() = a;
	f5().modify();//只是对临时对象的修改,并没有修改
	f7(f5());
	//f6() = x(1);//返回的const不可以作为左值
	//f6().modify();
   // f7(f6());//f7()中是引用需要引用f6()返回的临时对象的地址,所以会对临时对象进行修改所以此时编译器将临时对象置为const这就不可调用了
	f7(f5().f8());
}

#include<iostream>
using namespace std;


class x
{
	
};
x f()
{
	return x();
}

void g1(x &)
{
}
void g2(const x&)
{

}


void main()
{
	g1(f());
	g2(f());
}
对于上边的运行在vc6.0和vs2010中都是可以的,但是编译器一般将返回的临时变量当作一个常量,所以说g1(f());的调用应该是错误的但是,实际中却是正确的,所以多多实践试一试

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值