Question & Answer
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){ ... }
Was this topic helpful?
Document Information
Modified date:
06 December 2018
UID
swg21153090