[PATCH] D24639: [Sema] Warn when returning a lambda that captures a local variable by reference

Erik Pilkington via cfe-commits cfe-commits at lists.llvm.org
Thu Sep 15 15:54:30 PDT 2016


erik.pilkington created this revision.
erik.pilkington added reviewers: faisalv, rsmith.
erik.pilkington added a subscriber: cfe-commits.

Previously, clang emitted no diagnostic for the following:
```
auto f() {
  int loc;
  return [&] { return loc; };
}
```
The problem being that this returns a dangling reference to the local variable 'loc'. This patch warns on this by extending `-Wreturn-stack-address`.

This patch also warns on the following, where the lambda is stored in a variable:
```
auto f() {
  int loc;
  auto lam = [&loc] {};
  return lam; // warn
}
```
I believe that this is OK, I can't think of any valid way of mutating `lam` that would make the code not return a dangling pointer to `loc`.

Also, this diagnoses the following, where a pointer to a local is captured via an init-capture:
```
auto f() {
  int local;
  return [x = &local] {}; // warn
}
```
But not here, because we would have to verify that the pointer in `lam` wasn't mutated in a previous call of the lambda:
```
auto f() {
  int local;
  auto lam = [x = &local] {};
  return lam; // no warn
}
```

Thanks for taking a look!

https://reviews.llvm.org/D24639

Files:
  include/clang/AST/LambdaCapture.h
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/Sema/SemaChecking.cpp
  test/SemaCXX/cxx1y-generic-lambdas-capturing.cpp
  test/SemaCXX/cxx1y-init-captures.cpp
  test/SemaCXX/return-lambda-stack-addr.cpp

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D24639.71562.patch
Type: text/x-patch
Size: 11523 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20160915/c97593e5/attachment.bin>


More information about the cfe-commits mailing list