assignment operator - C++ function returns a rvalue, but that can be assigned a new value? -
the code follows:
#include <iostream> using namespace std; class { }; rtbyvalue() { return a(); } void passbyref(a &aref) { // nothing } int main() { aa; rtbyvalue() = aa; // compile without errors passbyref(rtbyvalue()); // compile error return 0; }
the g++ compiler gives following error:
d.cpp: in function ‘int main()’: d.cpp:19:23: error: invalid initialization of non-const reference of type ‘a&’ rvalue of type ‘a’ d.cpp:12:6: error: in passing argument 1 of ‘void passbyref(a&)’
it says can't pass rvalue argument of non-const reference, i'm confused why can assign rvalue, code shows.
passing rvalue rtbyvalue()
function expects lvalue reference doesn't work because require lvalue reference argument initialized rvalue. §8.5.3/5 describes how lvalue references can initialized – won't quote in full, says lvalue reference can initialized
- either lvalue reference
- or can converted lvalue reference of intermediary type
- or rvalue, if lvalue reference initialize const-reference
since argument need initialize not const-reference, none of applies.
on other hand,
rtbyvalue() = aa;
i.e., assigning temporary object, possible because of:
(§3.10/5) lvalue object necessary in order modify object except rvalue of class type can used modify referent under circumstances. [ example: member function called object (9.3) can modify object. — end example ]
so works because a
of class-type, , (implicitly defined) assignment operator member function. (see this related question further details.)
(so, if rtbyvalue()
return, example, int
, assignment wouldn't work.)
Comments
Post a Comment