Home > Backend Development > C++ > body text

## Does Binding a Const Reference to a Sub-Object of a Temporary Extend Its Lifetime?

DDD
Release: 2024-10-26 07:22:30
Original
503 people have browsed it

## Does Binding a Const Reference to a Sub-Object of a Temporary Extend Its Lifetime?

Binding Const Reference to a Sub-Object of a Temporary

Consider the following code:

<code class="cpp">#include <stdio.h>

struct P2d {
    double x, y;
    P2d(double x, double y) : x(x), y(y) {}
    ~P2d() { printf("Destructor called\n"); }
};

P2d center() {
    return P2d(10, 10);
}

int main(int argc, const char *argv[]) {
    const double& x = center().x;
    printf("x = %.18g\n", x);
    return 0;
}</code>
Copy after login

In this example, center() returns a temporary P2d object. The question arises: what is the lifetime of this temporary object?

Differences in Compiler Behavior

Different compilers exhibit different behaviors:

  • g (version 5.2.0) destroys the temporary P2d object before entering the printf in main. However, it preserves the value of its x member. Notably, it extends the lifetime of the temporary only if the subobject is of a class or array type.
  • clang extends the lifetime of the temporary P2d object to the lifetime of the x reference. Thus, the destructor is called after the printf in main.

According to the C standard, binding a reference to a sub-object of a temporary does not extend the temporary's lifetime. However, this is covered by CWG 1651, which proposes a change to extend the lifetime in such cases.

Pending Resolution

The status quo is that only prvalues are treated as referring to temporaries. However, member access expressions, like center().x, are considered prvalues by both g and clang .

  • g does not extend the lifetime when using scalar subobjects because [dcl.init.ref]/(5.2.1.1) does not cover them.
  • clang already implements the "new" lifetime extension rules, which will become the correct behavior once CWG 1651 is resolved.

The forthcoming resolution will clarify that member access expressions result in temporary expressions, and that binding a reference to these expressions extends the lifetime of the corresponding temporary object.

The above is the detailed content of ## Does Binding a Const Reference to a Sub-Object of a Temporary Extend Its Lifetime?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template