1
int a = 20;
int& fun(){
     return a;
}
int main(){
     fun();
     return 0;
}

Is the reference returned by func rvalue by itself?

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Vanconts
  • 45
  • 6

1 Answers1

3

No. If a function returns an lvalue reference, then calling it gives you an lvalue.

If it returns an rvalue reference, you get an xvalue, and if it returns by value, you get a prvalue.

Also, strictly saying the result of calling the function is not a reference. It's an lvalue expression of type int.


In general, you can determine value category of any expression by applying decltype to it. It will add reference-ness to the type of the expression, indicating its category: & for lvalues, && for xvalues, and nothing for prvalues.

Expressions themselves can't have reference types, so this added reference-ness will not conflict with their type.

For example, decltype(fun()) is int &, proving that it's an lvalue.

Even though doesn't apply in this case, note that decltype handles variable names differently from any other expressions (giving you the type of the variable, rather than expression type + value category). The workaround is to add a second set of (...) around the variable name, which makes decltype treat it as any other expression.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • So references can not be rvalues? Only lvalues? – Vanconts Jul 25 '20 at 19:36
  • @RostyslavBuryak Hmm. When you say "a reference", you normally mean a reference type (e.g. `int &`), or a variable that has a reference type (e.g. `int &x`). Value category (lvalues, rvalues, and other -values), on the other hand, is a property of an expression, an neither types nor variables are expressions. Yes, a variable name can be used as an expression (e.g. the second occurence of `b` in `int a=42; int &b = a; cout << b;` is an expression) - in that case the resulting expression is always an lvalue, regardless of whether the variable is reference or not, and if it's an rvalue reference. – HolyBlackCat Jul 25 '20 at 19:48
  • But you don't have reference variables in your question, so this doesn't help in this case. – HolyBlackCat Jul 25 '20 at 19:49
  • > *In general, you can determine value category of any expression by applying decltype to it.* If anyone's curious look at [this SO Answer](https://stackoverflow.com/questions/16637945/empirically-determine-value-category-of-c11-expression) – Waqar Jul 25 '20 at 19:59
  • @RostyslavBuryak I suggest figuring out the [terminology](https://en.cppreference.com/w/cpp/language/basic_concepts) first: what are "variables", "objects", "expressions", etc. – HolyBlackCat Jul 25 '20 at 20:12
  • @HolyBlackCat actually understanding that value category is a property of an expression really helps in understanding of value categories at all – Vanconts Jul 25 '20 at 21:07