Home  >  Article  >  Backend Development  >  Is Binding a Const Reference to a Temporary Sub-Object in C a Bug or Expected Behavior?

Is Binding a Const Reference to a Temporary Sub-Object in C a Bug or Expected Behavior?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 11:26:29822browse

Is Binding a Const Reference to a Temporary Sub-Object in C   a Bug or Expected Behavior?

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

  • GCC: Extends the lifetime only for class or array subobjects, based on CWG 1651 resolution.
  • Clang: Already implements the lifetime extension rules outlined in N3918, which extends the lifetime for all temporary subobjects.

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!

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