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.
The above is the detailed content of ## **Does Binding a Constant Reference to a Sub-Object of a Temporary Extend Its Lifetime? A Tale of GCC and Clang**. For more information, please follow other related articles on the PHP Chinese website!