It will not compile under gcc (4.6.3). I get the following error message:
test.cpp: In function ‘int main()’:
test.cpp:21:15: error: invalid initialization of non-const reference of type ‘myclass&’ from an rvalue of type ‘const myclass’
test.cpp:4:6: error: in passing argument 1 of ‘void foo(myclass&)’
It will compile with the call to foo() commented out. I do not understand why the const is allowing foobar to compile? Any ideas?
The standard says that temporary objects (rvalues) can be bound to const references, but not to non-const references. The object returned by create() is a temporary object.
This happens because an r-value can be bound to a const reference, but not to a non-const reference. And a temporary unnamed object returned by the create() function is an r-value.
By the way the code will be compiled successfully by MS VC++ 2010 if you will not switch off VC++ language extensions for the project.:)
I described peculiarities of the MS VC++ 2010 here
Thanks. Of course the standard is what it is, but do you have any idea of the philosophy behind this particular rule? What are they protecting against with this behavior?