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>
In this example, center() returns a temporary P2d object. The question arises: what is the lifetime of this temporary object?
Different compilers exhibit different behaviors:
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.
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 .
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!