Search code examples
c++c++11language-lawyerundefined-behaviorrvalue-reference

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?


Solution

  • No it is not undefined behavior (UB). It's fine - you can modify the contents of the temporary here (so long as the reference is valid for the lifetime of the temporary, in this case the bind to the rvalue reference extends that lifetime of the rvalue to the lifetime of the reference).

    A more general question is; is it UB to modify a temporary through the rvalue reference? No it is not UB. Move semantics, where the "moved-to" object "steals" the "moved-from" object's contents, relies on this to be well defined.