Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a function return-value constant by default (an rvalue)?

I'm learning about rvalue references, and the tutorial told me this:

X foo();
X x;
x = foo();

Rather obviously, it would be ok, and much more efficient, to swap resource pointers (handles) between x and the temporary, and then let the temporary's destructor destruct x's original resource.

In other words, in the special case where the right hand side of the assignment is an rvalue, we want the copy assignment operator to act like this.

So, does this mean that return values from functions are always constant by default, and thereby an rvalue? If yes: Are they always constant, or are there exceptions too?

like image 501
xcrypt Avatar asked Feb 03 '26 12:02

xcrypt


1 Answers

Rvalue-ness and constant-ness are not synonyms, but rather a bit orthogonal. With the following definitions:

struct X {};
const X x;
const X f();
int X();

We can categorize the following expressions:

x;       // constant lvalue
f();     // constant rvalue
g();     // non-constant rvalue

As of your particular question: no, not all rvalue expressions are constant.

like image 164
David Rodríguez - dribeas Avatar answered Feb 06 '26 04:02

David Rodríguez - dribeas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!