In C++11, programmers are given control over how lambdas capture values: each value used in the lambda expression (other than the arguments to the lambda itself) is captured either by reference or by value.

There are a couple of dangers here:

  • Capturing a temporary value by reference is not only legal, it fails to produce a compile warning even in the latest versions of GCC and Clang. This will, of course, cause a segfault as soon as the lambda is called.
  • Capturing a raw pointer by value may not be any safer than capturing it by reference, since the lambda has no control over the lifecycle of the pointed-to object. This is particularly dangerous when calling function methods inside a lambda, because there is no easy way to guarantee that the this pointer will still be valid.

Is there a static analysis tool that catches one or both of these cases? I'd expect the first problem to be pretty easy to catch, but it appears that clang-check -analyze (the only static analysis tool I've been able to try on my codebase so far) does not catch it.

A Windows tool would be acceptable, even if it requires an MSVC license, but I'd prefer something that can run on Debian Linux.

  • I'm not sure it matches your request but, for your first point, I think Viva64 can help you: viva64.com/en/w/v788 – Alex Placet Feb 22 '18 at 10:07
  • @AlexPlacet That does look interesting! I think the error cases referred to are kind of the opposite of what I'm talking about here, though, since the fix is to capture by reference. – Kyle Strand Feb 23 '18 at 17:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.