Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use rvalue reference to temporary? Is it undefined behavior or not?

Updating the question Why this two rvalue references examples have different behavior?:

Source code:

int a = 0;
auto && b = a++;
++a;
cout << a << b << endl;

prints 20

Is it undefined behavior (UB) to use b after the a++ call? Maybe we cannot use b because it refers to a temporary?

like image 710
vladon Avatar asked Feb 10 '16 12:02

vladon


1 Answers

The code is fine. b refers to a lifetime-extended object that is the result of the expression a++, which is a different object from a. (Binding a temporary object to a reference extends the lifetime of the object to that of the reference.) You can use and modify both objects.

like image 94
Kerrek SB Avatar answered Sep 16 '22 15:09

Kerrek SB