[clang] [Clang] correct error message when assigning to const reference captured in lambda (PR #105647)

via cfe-commits cfe-commits at lists.llvm.org
Thu Aug 22 05:13:31 PDT 2024


https://github.com/nfrmtk created https://github.com/llvm/llvm-project/pull/105647

Fixes:#98772

>From 4bb6969d0969ca9b4df20693107fbc1980c90f0f Mon Sep 17 00:00:00 2001
From: ivan lykov <nfrmtk.aka.fkfka at gmail.com>
Date: Thu, 22 Aug 2024 15:10:52 +0300
Subject: [PATCH] [Clang] correct error message when assigning to const
 reference captured in lambda

---
 clang/lib/Sema/SemaExpr.cpp               | 2 ++
 clang/test/SemaCXX/lambda-expressions.cpp | 5 +++++
 2 files changed, 7 insertions(+)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index c67183df335dd5..9c256fd1ed1a41 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -13140,6 +13140,8 @@ static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
   if (!var) return NCCK_None;
   if (var->getType().isConstQualified()) return NCCK_None;
+  if (var->getType()->isReferenceType())
+    return NCCK_None;
   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
 
   // Decide whether the first capture was for a block or a lambda.
diff --git a/clang/test/SemaCXX/lambda-expressions.cpp b/clang/test/SemaCXX/lambda-expressions.cpp
index acf8d014a9896b..612c6db950f273 100644
--- a/clang/test/SemaCXX/lambda-expressions.cpp
+++ b/clang/test/SemaCXX/lambda-expressions.cpp
@@ -189,6 +189,11 @@ namespace ModifyingCapture {
     [=] {
       n = 1; // expected-error {{cannot assign to a variable captured by copy in a non-mutable lambda}}
     };
+    const int cn = 0;
+    // cxx03-cxx11-warning at +1 {{initialized lambda captures are a C++14 extension}}
+    [&cnr = cn]{ // expected-note {{variable 'cnr' declared const here}}
+      cnr = 1; // expected-error {{cannot assign to variable 'cnr' with const-qualified type 'const int &'}}
+    };
   }
 }
 



More information about the cfe-commits mailing list