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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With