[clang-tools-extra] [clang-tidy] Improve `bugprone-capturing-this-in-member-variable` check: add support of `bind` functions. (PR #132635)
Baranov Victor via cfe-commits
cfe-commits at lists.llvm.org
Wed Mar 26 03:57:57 PDT 2025
================
@@ -87,33 +94,54 @@ void CapturingThisInMemberVariableCheck::registerMatchers(MatchFinder *Finder) {
// [self = this]
capturesVar(varDecl(hasInitializer(cxxThisExpr())))));
auto IsLambdaCapturingThis =
- lambdaExpr(hasAnyCapture(CaptureThis.bind("capture"))).bind("lambda");
- auto IsInitWithLambda =
- anyOf(IsLambdaCapturingThis,
- cxxConstructExpr(hasArgument(0, IsLambdaCapturingThis)));
+ lambdaExpr(hasAnyCapture(CaptureThis)).bind("lambda");
+
+ auto IsBindCapturingThis =
+ callExpr(
+ callee(functionDecl(matchers::matchesAnyListedName(BindFunctions))
+ .bind("callee")),
+ hasAnyArgument(cxxThisExpr()))
+ .bind("bind");
+
+ auto IsInitWithLambdaOrBind =
+ anyOf(IsLambdaCapturingThis, IsBindCapturingThis,
+ cxxConstructExpr(hasArgument(
+ 0, anyOf(IsLambdaCapturingThis, IsBindCapturingThis))));
+
Finder->addMatcher(
cxxRecordDecl(
anyOf(has(cxxConstructorDecl(
unless(isCopyConstructor()), unless(isMoveConstructor()),
hasAnyConstructorInitializer(cxxCtorInitializer(
isMemberInitializer(), forField(IsStdFunctionField),
- withInitializer(IsInitWithLambda))))),
+ withInitializer(IsInitWithLambdaOrBind))))),
has(fieldDecl(IsStdFunctionField,
- hasInClassInitializer(IsInitWithLambda)))),
+ hasInClassInitializer(IsInitWithLambdaOrBind)))),
unless(correctHandleCaptureThisLambda())),
this);
}
-
void CapturingThisInMemberVariableCheck::check(
const MatchFinder::MatchResult &Result) {
- const auto *Capture = Result.Nodes.getNodeAs<LambdaCapture>("capture");
- const auto *Lambda = Result.Nodes.getNodeAs<LambdaExpr>("lambda");
+ const auto EmitDiag = [this](const SourceLocation &Location,
+ const FunctionDecl *Bind) {
+ const std::string BindName = Bind ? Bind->getQualifiedNameAsString() : "";
+ diag(Location, "'this' captured by a %select{lambda|'%1' call}0 and "
+ "stored in a class member variable; disable implicit class "
+ "copying/moving to prevent potential use-after-free")
+ << (Bind ? 1 : 0) << BindName;
+ };
----------------
vbvictor wrote:
Now it may be clearer since we have only two `if`-s
https://github.com/llvm/llvm-project/pull/132635
More information about the cfe-commits
mailing list