[clang] [clang] Fix lifetime extension of temporaries in for-range-initializers in templates (PR #177191)

via cfe-commits cfe-commits at lists.llvm.org
Wed Jan 21 08:28:04 PST 2026


================
@@ -3017,6 +3009,13 @@ StmtResult Sema::BuildCXXForRangeStmt(
   if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
     OpenMP().ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get());
 
+  // P2718R0 - Lifetime extension in range-based for loops.
----------------
yronglin wrote:

Eg.

The lifetime of temporary in for-range-init was not extended. Because the sema will not ran into this branch: https://github.com/llvm/llvm-project/blob/e2d7cd685d40edd302da7396d9b9c97087e6ff20/clang/lib/Sema/SemaStmt.cpp#L2731

```cpp
template <typename T>
int test1() {
    int x = 5;
    int sum = 0;
    for (int _ : f1(g(x))) sum += x;
    sum += x;
    return sum;
}
```

But lifetime of the temporary in this for-range-init was correct extended:
```cpp
template <typename T>
T test1() {
    T x = 5;
    T sum = 0;
    for (T _ : f1(g(x))) sum += x;
    sum += x;
    return sum;
}
```

So just simply move the lifetime extension logic will fix this issue.

https://github.com/llvm/llvm-project/pull/177191


More information about the cfe-commits mailing list