Skip to content

C++: Do not use [=] or [=,this] to capture 'this' #543

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: gh-pages
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions cppguide.html
Original file line number Diff line number Diff line change
Expand Up @@ -3479,7 +3479,8 @@ <h3 id="CTAD">Class template argument deduction</h3>
<h3 id="Lambda_expressions">Lambda expressions</h3>

<p>Use lambda expressions where appropriate. Prefer explicit captures
when the lambda will escape the current scope.</p>
when the lambda will escape the current scope. Do not use <code>[=]</code>
or <code>[=, this]</code> to capture <code>this</code>.</p>

<p class="definition"></p>
<p> Lambda expressions are a concise way of creating anonymous
Expand Down Expand Up @@ -3555,13 +3556,19 @@ <h3 id="Lambda_expressions">Lambda expressions</h3>
<p class="cons"></p>
<ul>
<li>Variable capture in lambdas can be a source of dangling-pointer
bugs, particularly if a lambda escapes the current scope.</li>

<li>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.</li>
bugs, particularly if a lambda escapes the current scope. Default capture
by reference (<code>[&amp;]</code>) makes such bugs easier to introduce.</li>

<li>Default capture by value (<code>[=]</code>) 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.</li>

<li>Capturing <code>this</code> along with default capture by value is
especially confusing, and strict support among C++ versions is incompatible.
If capturing <code>this</code> (either explicitly or with by-reference
capture default), list any by-value captures explicitly. Keep in mind that
uses of captured <code>this</code> are often implicit.</li>

<li>Captures actually declare new variables (whether or not the captures have
initializers), but they look nothing like any other variable declaration
Expand Down