Skip to content

C++23 lifetime extension in range-based for loops: Clang destroys temporaries bound to references by default member initializer early (without warning) #85613

Closed
@hubert-reinterpretcast

Description

@hubert-reinterpretcast

Clang normally warns that it fails to extend the lifetime of temporaries bound to member references by default member initializers in aggregate initialization.
It fails to even warn when the aggregate initialization occurs as a subexpression of a for-range-initializer.

Online compiler link (with two cases: one where the aggregate initialization occurs as a subexpression and another where it is the for-range-initializer): https://godbolt.org/z/T9zdrevv8

SOURCE (<stdin>):

extern "C" void exit(int);

struct A {
  int arr[1];
  ~A() noexcept(false) { throw 42; }
};

struct B {
  int x;
  const A &a = A{{0}};
  const int *begin() { return a.arr; }
  const int *end() { return &a.arr[1]; }
};

int main() {
  for (auto &&x : B{0}.a.arr) { exit(0); }
  //for (auto &&x : B{0}) { exit(0); }
}

COMPILER INVOCATION:

clang++ -std=c++23 -Werror -xc++ -

COMPILER OUTPUT:

(clean compile with no warnings)

ACTUAL RUN OUTPUT:

$ ./a.out
libc++abi: terminating due to uncaught exception of type int

EXPECTED RUN OUTPUT:

rc = 0

COMPILER VERSION INFO (clang++ -v):

clang version 19.0.0git (https://github.com/llvm/llvm-project.git c0d03d28c58f3016eb25ce8d1160e11183d01735)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /opt/wandbox/clang-head/bin
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/10
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9
Selected GCC installation: /usr/lib/gcc/x86_64-linux-gnu/10
Candidate multilib: .;@m64
Selected multilib: .;@m64

Metadata

Metadata

Assignees

Labels

c++23clang:diagnosticsNew/improved warning or error message in Clang, but not in clang-tidy or static analyzerclang:frontendLanguage frontend issues, e.g. anything involving "Sema"

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions