Search code examples
c++lvaluervalue

How to test lvalue or rvalue in this case


The code is as following:

struct A
{
   static int k;
   int i;
};
 
int A::k = 10;
 
A func() { A a; return a; }

My question is, how can I tell whether func().k or func().i is an lvalue or not? If both are lvalues/rvalues, how can I test them?

func().k = 0; // compile ok under g++-4.4 and g++-4.6
func().i = 1; // compile ok with g++-4.4, but g++-4.4 gives an error: 
              //"using temporary as lvalue [-fpermissive]"

Solution

  • func().k is an lvalue and func().i is an xvalue.

    You can see this for more details: rvalues and temporary objects in the FCD

    Althrough, it is not difficult to test whether they are lvalues or rvalues:

    #include <iostream>
    
    struct A
    {
        static int k;
        int i;
    };
    
    int A::k = 10;
    
    A func( ){ A a; return a; }
    
    void f (int & ) { std::cout << "int& " << std::endl; }
    
    int main ()
    {
        func().k = 0;  //ok, because func().k is an r
        f(func().k);
        func().i = 1; //compile error: "using temporary as lvalue"
        f(func().i);  //compile error because func().i is an rvalue of type ‘int’
        return 0;
    }