The behavior when binding a constant reference to a sub-object of a temporary is defined by the C standard and varies depending on the compiler vendor.
According to CWG 1651, the result of a member access or subscript expression applied to a prvalue should be treated as an xvalue. This implies that binding a reference to such a subobject of a temporary should not extend the lifetime of the temporary.
However, in the example provided, both compilers treat center().x as a prvalue. GCC does not extend lifetime when using scalar subobjects because they are not covered by [dcl.init.ref]/(5.2.1.1). Hence, the temporary object can be destroyed early.
In contrast, Clang has implemented the pending resolution to DR 1651, which states that if E1 is a temporary expression and E2 does not designate a bit-field, then E1.E2 is a temporary expression. As center() is a temporary expression according to this definition, the modified wording in [class.temporary] /5 applies. It explicitly states that the corresponding temporary object persists for the lifetime of the reference.
Therefore, Clang extends the lifetime of the temporary P2d instance in this case, while GCC does not.
The current behavior in both GCC and Clang is expected to change once the proposed revisions to the C standard are adopted.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3