Home > front end >  Return of a func
Return of a func

Time:04-27

Consider this code:

#include <iostream>
using namespace std;

class Rectangle {
    int width, height;
  public:
    Rectangle() {}
    Rectangle (int x, int y) : width(x), height(y) {}
    int area() {return width * height;}
    friend Rectangle duplicate (const Rectangle&);
};

Rectangle duplicate (const Rectangle& param)
{
  Rectangle res;
  res.width = param.width*2;
  res.height = param.height*2;
  return res;
}

int main () {
  Rectangle foo;
  Rectangle bar (2,3);
  foo = duplicate (bar);
  cout << foo.area() << '\n';
  return 0;
}

There is a friend function in line 14. this function declares an object inside its body. and at the the end returns that object. Now I wonder if the return of this function is an rvalue or lvalue?

CodePudding user response:

Please keep it in mind that value category is a property of an expression, not "a value".

res, as an id-expr, is lvalue. However, the duplicate (bar) function call expression is a rvalue, for all the functions calls returning non-reference are prvalues.

CodePudding user response:

I wonder if the return of this function is an rvalue or lvalue?

It is an rvalue. From value category:

The following expressions are prvalue expressions:

  • a function call or an overloaded operator expression, whose return type is non-reference...

This means that the call expression duplicate (bar) is an rvalue.


Also note that res itself is an lvalue expression.

  • Related