From bacabed1adb81d6bd312a3345a80bd4b66bc027e Mon Sep 17 00:00:00 2001
From: Peter Dillinger
Date: Tue, 14 Apr 2020 10:41:30 -0700
Subject: [PATCH] C++: Do not use [=] or [=,this] to capture 'this'
Summary: C++20 deprecates [=] capturing 'this'
(http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0806r2.html)
but the recommended alternative [=,this] is not standards-legal prior to
C++20 (though it is widely accepted *with warning*).
For portability (and readability), style should forbid using
[=] or [=,this] to capture 'this'. Any by-value captures must be
explicitly listed if also capturing 'this', though 'this' can still
be implicitly default-captured by reference, as in
[&, some_var_to_copy].
Test Plan: documentation only
---
cppguide.html | 21 ++++++++++++++-------
1 file changed, 14 insertions(+), 7 deletions(-)
diff --git a/cppguide.html b/cppguide.html
index bbf1f64..761194c 100644
--- a/cppguide.html
+++ b/cppguide.html
@@ -3479,7 +3479,8 @@ array(T, U...) -> std::array<T, 1 + sizeof...(U)>;
Lambda expressions
Use lambda expressions where appropriate. Prefer explicit captures
-when the lambda will escape the current scope.
+when the lambda will escape the current scope. Do not use [=]
+or [=, this]
to capture this
.
Lambda expressions are a concise way of creating anonymous
@@ -3555,13 +3556,19 @@ std::sort(indices.begin(), indices.end(), [&](int a, int b) {
- Variable capture in lambdas can be a source of dangling-pointer
- bugs, particularly if a lambda escapes the current scope.
+ bugs, particularly if a lambda escapes the current scope. Default capture
+ by reference ([&]
) makes such bugs easier to introduce.
- - Default captures by value can be misleading because they do not prevent
- dangling-pointer bugs. Capturing a pointer by value doesn't cause a deep
- copy, so it often has the same lifetime issues as capture by reference.
- This is especially confusing when capturing 'this' by value, since the use
- of 'this' is often implicit.
+ - Default capture by value (
[=]
) can be misleading because
+ it does not prevent dangling-pointer bugs. Capturing a pointer by value
+ doesn't cause a deep copy, so it has essentially the same lifetime issues
+ as capture by reference.
+
+ - Capturing
this
along with default capture by value is
+ especially confusing, and strict support among C++ versions is incompatible.
+ If capturing this
(either explicitly or with by-reference
+ capture default), list any by-value captures explicitly. Keep in mind that
+ uses of captured this
are often implicit.
- Captures actually declare new variables (whether or not the captures have
initializers), but they look nothing like any other variable declaration