This code does not compile:
class C {};
void foo (C& c) {}
C bar() { return C(); }
int main()
{
foo(bar());
}
Compilation error (GCC 4.1.2) in line foo(bar()):
invalid initialization of non-const reference of type ‘C&’
from a temporary of type ‘C’
As bar() returns a mutable object, it should compile…
Why C++ does not allow this above code?
EDIT: I have summarize in an answer below all good ideas from all answers 😉
The applicable rule here is that you can’t create a non-const reference to a temporary object. If
foowas declared asfoo(const C&)the code would be okay.The temporary object itself is not const, though; you can call non-const member functions on it, e.g.,
bar().non_const_member_function().With C++11, foo can be written to take an rvalue reference; in that case, the call would be okay: