Home  >  Article  >  Backend Development  >  ## Does Binding a Const Reference to a Sub-Object of a Temporary Extend Its Lifetime in C ?

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

DDD
DDDOriginal
2024-10-26 04:20:02410browse

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

About Binding a Const Reference to a Sub-Object of a Temporary

In C code like this:

<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>

Different compilers behave differently regarding the lifetime of the temporary object center(). GCC destroys the temporary before entering printf in main, while Clang extends its lifetime to match that of the reference x. However, if replaced with a custom class Double for the x and y members, both compilers agree and extend the temporary's lifetime.

Standard Considerations

This behavior is addressed by CWG 1651, which states that the result of member access or subscript expression applied to a prvalue is an xvalue, and binding a reference to such a subobject of a temporary should not extend its lifetime. While both compilers treat center().x as a prvalue, they do not fully implement the change proposed by CWG 1651.

Compiler Differences

GCC

  • Does not extend lifetime for scalar subobjects because they are not considered temporaries under [dcl.init.ref]/(5.2.1.1).

Clang

  • Recognizes member access and already implements the lifetime extension rules, even handling casts.

Future Standard Changes

N3918, a pending resolution to DR 1651, would clarify that accessing a temporary via member expression should extend its lifetime. Once adopted, this change would align Clang's behavior with the standard.

The above is the detailed content of ## Does Binding a Const Reference to a Sub-Object of a Temporary Extend Its Lifetime in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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