IBM Support

Reference to a non-const object cannot be initialized with an r-value of that object

Technote (FAQ)


Question

My program fails to compile with an error message indicating that a reference to a non-const object cannot be initialized with an r-value of that object. What is the rationale behind this compiler behavior?

Answer

class A{};
A f(){
    A a;
    return a;
}

void g(A &a){ }    // ill-formed for g(f())

int main(){
    g(f());
}

xlC t.cpp

"t.cpp", line 11.9: 1540-0295 (S) A parameter of type "A &" cannot be initialized with an rvalue of type "A".
"t.cpp", line 11.9: 1540-1290 (I) An rvalue cannot be converted to a reference to a non-const type.
"t.cpp", line 11.9: 1540-1205 (I) The error occurred while converting to parameter 1 of "g(A &)".

The C++ Standard section 3.10:5 indicates that the result of calling a function that does not return a reference is an rvalue. Therefore, in main(), the function f() returns an rvalue, an instance of class A. An rvalue does not have an address and you cannot store into it. According to section 13.3.3.1.4:3 a standard conversion sequence cannot be formed if it requires binding a non-const reference to an rvalue, except for implicit object parameters.

To correct this problem a const reference must be used as the function parameter. The sample above, function g() would be declared or overloaded as follows:

void g(const A &a){ ... }

Cross reference information
Segment Product Component Platform Version Edition
Software Development XL C/C++ for AIX Compiler AIX All Versions Not applicable
Software Development XL C/C++ for Linux Compiler Linux All Versions Not Applicable

Document information

More support for: XL C/C++
Compiler

Software version: All Versions

Operating system(s): AIX, Linux, OS X

Reference #: 1153090

Modified date: 29 November 2004


Translate this page: