https://github.com/hokein created https://github.com/llvm/llvm-project/pull/117733
Fixes #117728 >From bf697889ec6681dffc22120fef6d49ffddbd0b87 Mon Sep 17 00:00:00 2001 From: Haojian Wu <hokein...@gmail.com> Date: Tue, 26 Nov 2024 17:14:49 +0100 Subject: [PATCH] [clang] Don't warn if the capturing object is also temporary. --- clang/lib/Sema/SemaChecking.cpp | 10 +++++++--- clang/test/Sema/warn-lifetime-analysis-capture-by.cpp | 11 +++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index a49605e4867651..54d8bbdfc0f4fd 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -3248,9 +3248,13 @@ void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction, checkCaptureByLifetime(*this, CE, Captured); } }; - for (unsigned I = 0; I < FD->getNumParams(); ++I) - HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(), - I + IsMemberFunction); + // Suppress the warning if the capturing object is also a temporary to reduce + // noise, e.g `vector<string_view>().push_back(std::string());`. + if (!isa_and_present<MaterializeTemporaryExpr>(ThisArg)) { + for (unsigned I = 0; I < FD->getNumParams(); ++I) + HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(), + I + IsMemberFunction); + } // Check when the implicit object param is captured. if (IsMemberFunction) { TypeSourceInfo *TSI = FD->getTypeSourceInfo(); diff --git a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp index 4d562bac1e305b..61d13c9e585e44 100644 --- a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp +++ b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp @@ -143,6 +143,17 @@ void use() { } } // namespace this_is_captured +namespace ignore_temporary_class_object { +struct S { + void add(const int& x [[clang::lifetime_capture_by(this)]]); +}; + +void test() { + S().add(1); + S{}.add(1); +} +} // namespace ignore_temporary_class_object + // **************************************************************************** // Capture by Global and Unknown. // **************************************************************************** _______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits