Binding a Const Reference to a Temporary Sub-Object: A Conundrum
The C code snippet below demonstrates a discrepancy in behavior between different compilers when attempting to bind a const reference to a sub-object of a temporary:
<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; // Bind a reference to temporary's x member printf("x = %.18g\n", x); // Expected: 10 return 0; }</code>
Bug or Expected Behavior?
Compilers like g terminate the lifetime of the temporary P2d instance prior to entering the printf in main, but the double member x's value is still preserved. This is achieved by creating another temporary double to copy the value instead of binding to the original temporary's member.
On the other hand, clang correctly extends the lifetime of the P2d temporary to match that of the x reference, allowing the destructor to be called after the printf in main.
This discrepancy poses the question: is g 's behavior a bug or permissible under the C standard?
Analysis and Solution
CWG 1651 sheds light on this issue:
Binding a reference to a sub-object should not extend the lifetime of temporary objects.
Under current standards, objects other than scalars, such as classes or arrays, can extend the temporary object's lifetime.
Compiler Behavior
Conclusion
Based on the current wording of the C standard, GCC's behavior is technically correct, while Clang's implementation reflects the proposed changes in DR 1651. It is likely that the standard will be revised to reflect this change in the future.
The above is the detailed content of Is Binding a Const Reference to a Temporary Sub-Object in C a Bug or Expected Behavior?. For more information, please follow other related articles on the PHP Chinese website!