闲工夫时候思考之C++的临时量
空闲时候思考之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());的调用应该是错误的但是,实际中却是正确的,所以多多实践试一试
版权声明:本文为博主原创文章,未经博主允许不得转载。