llvm / llvm/llvm-project

[clang]Clang rejects reference member initialized by temporary via default member initializer

Open
#185,874 6 comments 0 reactions 1 assignee Claimed by @yronglin View on GitHub
clang:frontend diverges-from:edg diverges-from:gcc diverges-from:msvc
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

Clang rejects this valid C++ code, while GCC, MSVC, and EDG accept it.

```cpp
struct A { int arr[1]; };

struct B { const A& a = A{{0}}; };

B x;
int v = x.a.arr[0];
```

https://godbolt.org/z/vrrYcMWP6
Clang reports that the reference member binds to a temporary whose lifetime would be shorter than the constructed object.

However, the temporary should have its lifetime extended because it is bound to a reference member during object initialization (the default member initializer is equivalent to a constructor mem-initializer). Therefore the temporary should persist for the lifetime of the reference member.

References:
- https://eel.is/c++draft/class.temporary#note-5
- https://cplusplus.github.io/CWG/issues/1696.html

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.