Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is a temporary l-value or not?

Tags:

c++

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);
}
like image 715
mhk Avatar asked Mar 31 '13 17:03

mhk


People also ask

What is an L value in C?

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

What is L value expression?

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.

Is the return value temporary?

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.

What are r values and l values?

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.


1 Answers

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.

like image 181
fredoverflow Avatar answered Oct 29 '22 07:10

fredoverflow