Search code examples
c++pointersreferencelvalue

Return value of a function not recognized as lvalue


Here's an example:

void foo(int*& x) {}

struct boo  
{  
  int* z;  
  int* getZ() { return z; }  
};

int main()
{
  int* y;
  foo(y);  // Fine

  boo myBoo;
  foo(myBoo.getZ());  // Won't compile

  return 0;
}

I can fix this by having boo::getZ() return a reference to a pointer, but I'm trying to understand what the difference is between the two parameters being passed in to foo(). Is the int* being returned by boo::getZ() not an lvalue? If so, why not?


Solution

  • If T is an object type and f is declared as...

    T &  f();                                          f() is an lvalue
    T && f();                     then                 f() is an xvalue
    T    f();                                          f() is a prvalue
    

    So getZ() is a prvalue (T = int *), which is an rvalue, and not an lvalue.