Why does the first line in main compiles but the second doesn't? Both are temporaries I think but one is treated as l-value and the other not..
class complex
{
public:
complex() : r(0),i(0) {}
complex(double r_, double i_) : r(r_), i(i_)
{
}
private:
double r;
double i;
};
int main()
{
complex(2,2) = complex(1,2);
char() = char(2);
}
lvalue simply means an object that has an identifiable location in memory (i.e. having an address). In any assignment statement “lvalue” must have the capability to store the data. lvalue cannot be a function, expression (like a+b) or a constant (like 3 , 4 , etc.).
Expressions that refer to memory locations are called "l-value" expressions. An l-value represents a storage region's "locator" value, or a "left" value, implying that it can appear on the left of the equal sign (=). L-values are often identifiers.
Formally: the return value is always a temporary. In contexts where that temporary is used as the argument of a copy constructor (the object is copied), the standard gives explicit authorization for the compiler to elide the copy, “merging” the temporary with the named variable it is initializing.
An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address). rvalues are defined by exclusion. Every expression is either an lvalue or an rvalue, so, an rvalue is an expression that does not represent an object occupying some identifiable location in memory.
On class types, the assignment operator is a member function. That is, a = b
is just syntatic sugar for a.operator=(b)
. And it is perfectly fine to call member functions on temporaries.
Please note that in C++, the term lvalue has nothing to do with the left-hand side of an assignment. As your example demonstrates, it is perfectly fine to assign to rvalues of class type. Also, there are lvalues which you cannot assign to, for example arrays and/or constants, especially string literals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With