after doing some test-code for this link :
Is it safe to call temporary object's methods?
I found a rather strange feature of the c++ language, which I’m not sure how it works :
struct Test{ int i; Test(int ii):i(ii){} Test& operator=(int ii){ i = ii; return *this; } Test operator+(const Test& rhs){ return Test(i + rhs.i); } void non_const_function(){ i *= i; } }; int main(){ //code below gives errors, builtin types don't allow evil code //int i = 5+5 = 8; //int& iRef = 5+5; //int* iPtr = &(5+5); //5 = 10; Test x = Test(5) + Test(5) = 8;//assign to a temporary Test& xRef = Test(5) + Test(5);//reference to a temporary Test* xPtr = &(Test(5) + Test(5));//address of a temporary Test(5) = Test(10);//assign to a temporary Test(8).non_const_function();//call a non-const function return 0; }
xRef and xPtr are both working pointers, with the expected values.
Of course I wouldn’t write such code in a real project, but I’m still interested how / why this works.
The only info I found on google about this was that ‘if you create a reference to a temporary, the temporaries lifetime is linked to the lifetime of the reference’
Note :
-not all compilers are that forgiving, e.g. Metrowerks ARM (does it use GCC ?) only allows const reference to temporaries.
EDIT :
-increasing the warning to W4 in VC++ 2008 showed lots of errors – good to know.
EDIT 2:
Thank you all for the help. I’m back to work, fixing 100’s of warnings.
CONCLUSION : use highest warning from start (I even found a REAL bug thanks to /G4)
Let’s go line by line:
There’s no big deal here. Temporaries are still just normal objects, and thus the assignment operator works on them just as it would on anything else.
Like Metroworks, my GCC doesn’t allow a non-const reference to a temporary.
In addition, GCC warns about taking the address of a temporary, for obvious reasons.
Again, this is just assignment, which, as I explained above, is no big deal.
Temporary objects aren’t constant. There’s nothing stopping them from calling non-const functions.