Apparently GCC catches it also. Here's my expected results before compiling and before reading others' comments:
1. Without using a compiler look at the code. Would you expect any warnings or errors from the compiler? Why?
"test_func() = one;
"- Some kind of 'Assigning to r-value/temporary' warning
, since test_func() isn't returning by reference.
should be test_func()
, no need for the 'void' there. I don't know if a warning will result. Probably something like "explicit void argument - compile with -ANSI to disable warning
2. What would you expect the output to be if it compiled?
Undefined gibberish value - whatever 'static number v
' initially resolves to, because it has never been assigned anything.
3. Now compare your results to what actually happens when you compile it. Is it what you expected?
Using GCC/MinGW 4.7.2:
I didn't get the warning I expected on assigning "test_func() = one;
instead I got an *error* on on the member variable assignment version: "test_func().x += 1.0f;
" error: using temporary as lvalue [-fpermissive]
I only found out yesterday that this is valid and standardized C++:
const int &refToTemp = 357;
...it just only lasts to the end of the scope that the expression is contained in. Still it's useful for avoiding a copy in some circumstances, which is why I looked it up:
//Only makes a copy if 'condition' is false.
const std::string &myString = ( ...condition... ? this->memberString : this->GetCopyOfSubStr_ReturnByValue());
Edited by Servant of the Lord, 26 January 2013 - 09:31 AM.