Reference to an unnamed temporary object (life time)

前端 未结 3 1412
醉话见心
醉话见心 2021-01-14 00:04

After reading this answer from ildjarn, I wrote the following example, and it looks like an unnamed temporary object has the same life time as its reference!

  • H
3条回答
  •  旧时难觅i
    2021-01-14 00:29

    How come this is possible?

    Because the standard says so, because it's deemed useful. rvalue references and const lvalue references extend the lifetime of temporaries:

    [C++11: 12.2/5]: [..] 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, except [..]

    and exhaustive wording in [C++11: 8.5.3/5] requires that we shall not bind temporaries to non-const lvalue references.


    Is it specified in the C++ standard? Which version?

    Yes. All of them.

提交回复
热议问题