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

后端 未结 3 1586
感情败类
感情败类 2021-02-13 20:55

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

Source code:

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


        
相关标签:
3条回答
  • 2021-02-13 21:26

    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.

    0 讨论(0)
  • 2021-02-13 21:33

    Taking a reference to a temporary extends its lifetime to the end of lifetime of that reference.

    ISO/IEC 14882 § 12.2/5:

    The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference […]

    0 讨论(0)
  • 2021-02-13 21:41

    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.

    0 讨论(0)
提交回复
热议问题