Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between lvalue reference and rvalue reference

I have been studying addition of rvalue reference in C++11. It wasn't straightforward but I feel like I am finally starting to get a grasp of it. However there is one particular instance where I am confused. Specifically I don't get what is the meaning of 'b' in this example:

int a = 27;
int&& b = 27;

EDIT: I know that int a = 27 is an lvalue not lvalue reference.

Also what I looking for is not what int&& b = 27 is but what is it meaning intuitively. I am confused because I thought that rvalues where not addressable, but here we have a reference to rvalue which means we can adress it. So how come it is still an rvalue?

like image 532
dawid Avatar asked Dec 23 '22 07:12

dawid


2 Answers

int a = 27; is a statement, and is neither an lvalue nor an rvalue. It defines the name a, which can be used as an lvalue expression, of type int.

int&& b = 27; is also a statement and the name b is used as an lvalue expression of type int&&, and permits a conversion to an xvalue expression of type int

like image 84
Caleth Avatar answered Dec 28 '22 06:12

Caleth


but here we have a reference to rvalue which means we can adress it. So how come it is still an rvalue?

Given int&& b = 27;, a temporary int is constructed from 27 and then b binds to the temporary. (And the lifetime of the temporary is extended to the lifetime of b.) After that if you get the address like &b you'll get the address of the temporary.

BTW b is an lvalue itself.

Temporary objects are created when a prvalue is materialized so that it can be used as a glvalue, which occurs (since C++17) in the following situations:

  • binding a reference to a prvalue

BTW: It's not special for rvalue reference; same thing happens for const int& b = 27;.

like image 36
songyuanyao Avatar answered Dec 28 '22 08:12

songyuanyao