Assigning to temporary (like 5 = 10 but for user-defined types)
<p>after doing some test-code for this link :<br />
<a href="http://stackoverflow.com/questions/701313/is-it-safe-to-call-temporary-objects-methods">http://stackoverflow.com/questions/701313/is-it-safe-to-call-temporary-objects-methods</a><br />
I found a rather strange feature of the c++ language, which I'm not sure how it works :</p>

<pre><code>struct Test{
    int i;
    Test(int ii):i(ii){}
    Test&amp; operator=(int ii){
     i = ii;
     return *this;
    }
    Test operator+(const Test&amp; 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&amp; iRef = 5+5;
        //int* iPtr = &amp;(5+5);
        //5 = 10;

        Test x = Test(5) + Test(5) = 8;//assign to a temporary
        Test&amp; xRef = Test(5) + Test(5);//reference to a temporary
        Test* xPtr = &amp;(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;
}
</code></pre>

<p>xRef and xPtr are both working pointers, with the expected values.<br />
Of course I wouldn't write such code in a real project, but I'm still interested how / why this works.<br />
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"  </p>

<p>Note :<br />
-not all compilers are that forgiving, e.g. Metrowerks ARM (does it use GCC ?) only allows const reference to temporaries.<br />
EDIT :<br />
-increasing the warning to W4 in VC++ 2008 showed lots of errors - good to know.  </p>

<p>EDIT 2:<br />
Thank you all for the help. I'm back to work, fixing 100's of warnings.<br />
CONCLUSION : use highest warning from start (I even found a REAL bug thanks to /G4)</p>
