Search code examples
c++return-valuervalue-referencetemporary-objectspass-by-rvalue-reference

Is return by value always const?


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 ;-)


Solution

  • The applicable rule here is that you can't create a non-const reference to a temporary object. If foo was declared as foo(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:

    void foo(C&&);
    foo(bar());  // okay