[clang] Add warning for blocks capturing {'this', raw pointers, references} (PR #144388)

Sylvain Defresne via cfe-commits cfe-commits at lists.llvm.org
Thu Jul 3 01:27:27 PDT 2025


================
@@ -1641,6 +1641,17 @@ def warn_implicitly_retains_self : Warning <
   "block implicitly retains 'self'; explicitly mention 'self' to indicate "
   "this is intended behavior">,
   InGroup<DiagGroup<"implicit-retain-self">>, DefaultIgnore;
+def warn_blocks_capturing_this : Warning<"block implicitly captures 'this'">,
+                                 InGroup<DiagGroup<"blocks-capturing-this">>,
+                                 DefaultIgnore;
+def warn_blocks_capturing_reference
+    : Warning<"block implicitly captures a C++ reference">,
+      InGroup<DiagGroup<"blocks-capturing-reference">>,
+      DefaultIgnore;
+def warn_blocks_capturing_raw_pointer
+    : Warning<"block implicitly captures a raw pointer">,
----------------
sdefresne wrote:

Okay. I'll investigate defining and using a new attributes.

Do you think this should be an attributes on the captured variables e.g. `__attribute__((capturable)) void* userData` or on the block e.g. `__attribute__((can_capture_pointers)) auto dispose = ^{ ... };` or both?

On one hand an attribute on the variable would make it difficult to silence the warnings about capturing `this` (since `this` is implicitly available, it is not easy to mark it with the attribute), and would probably require defining a local variable `_this` and mark it with the attribute.

On the other hand an attribute on the block would probably make it too easy to silence all the warnings.

Finally, I have a question about process. Should I summarize all the discussion in the issue #143924? Should I write a formal design document for the warning or is the github issue enough?

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


More information about the cfe-commits mailing list