IBM Support

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

Question & Answer


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?


class A{};

A f(){
    A a;
    return a;

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

int main(){

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 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){ ... }

[{"Product":{"code":"SSJT9L","label":"XL C\/C++"},"Business Unit":{"code":"BU054","label":"Systems w\/TPS"},"Component":"Compiler","Platform":[{"code":"PF002","label":"AIX"},{"code":"PF016","label":"Linux"},{"code":"PF022","label":"OS X"}],"Version":"All Versions","Edition":"","Line of Business":{"code":"LOB08","label":"Cognitive Systems"}},{"Product":{"code":"SSGH3R","label":"XL C\/C++ for AIX"},"Business Unit":{"code":"BU058","label":"IBM Infrastructure w\/TPS"},"Component":"Compiler","Platform":[{"code":"PF002","label":"AIX"}],"Version":"All Versions","Edition":"Not applicable","Line of Business":{"code":"LOB08","label":"Cognitive Systems"}},{"Product":{"code":"SSXVZZ","label":"XL C\/C++ for Linux"},"Business Unit":{"code":"BU058","label":"IBM Infrastructure w\/TPS"},"Component":"Compiler","Platform":[{"code":"PF016","label":"Linux"}],"Version":"All Versions","Edition":"Not Applicable","Line of Business":{"code":"LOB57","label":"Power"}}]

Document Information

Modified date:
06 December 2018