Home > Backend Development > C++ > ## **Does Binding a Constant Reference to a Sub-Object of a Temporary Extend Its Lifetime? A Tale of GCC and Clang**

## **Does Binding a Constant Reference to a Sub-Object of a Temporary Extend Its Lifetime? A Tale of GCC and Clang**

Barbara Streisand
Release: 2024-11-01 06:58:02
Original
569 people have browsed it

##  **Does Binding a Constant Reference to a Sub-Object of a Temporary Extend Its Lifetime? A Tale of GCC and Clang**

Binding a Constant Reference to a Sub-Object of a Temporary

Standard Behavior

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.

GCC and Clang Differences

  • GCC (version 5.2.0): Destroys the temporary P2d instance before entering printf in main, preserving the value by creating another temporary double.
  • Clang (version X): Extends the lifetime of the temporary P2d instance to the lifetime of the x reference, calling the destructor after printf in main.

Explanations

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.

Conclusion

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template