Debian Codegraph @

clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/misleading-capture-default-by-value.rst

raw
1 .. title:: clang-tidy - cppcoreguidelines-misleading-capture-default-by-value
2
3 cppcoreguidelines-misleading-capture-default-by-value
4 =====================================================
5
6 Warns when lambda specify a by-value capture default and capture ``this``.
7
8 By-value capture defaults in member functions can be misleading about whether
9 data members are captured by value or reference. This occurs because specifying
10 the capture default ``[=]`` actually captures the ``this`` pointer by value,
11 not the data members themselves. As a result, data members are still indirectly
12 accessed via the captured ``this`` pointer, which essentially means they are
13 being accessed by reference. Therefore, even when using ``[=]``, data members
14 are effectively captured by reference, which might not align with the user's
15 expectations.
16
17 Examples:
18
19 .. code-block:: c++
20
21 struct AClass {
22 int member;
23 void misleadingLogic() {
24 int local = 0;
25 member = 0;
26 auto f = [=]() mutable {
27 local += 1;
28 member += 1;
29 };
30 f();
31 // Here, local is 0 but member is 1
32 }
33
34 void clearLogic() {
35 int local = 0;
36 member = 0;
37 auto f = [this, local]() mutable {
38 local += 1;
39 member += 1;
40 };
41 f();
42 // Here, local is 0 but member is 1
43 }
44 };
45
46 This check implements `F.54
47 <https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#f54-when-writing-a-lambda-that-captures-this-or-any-class-data-member-dont-use--default-capture>`_
48 from the C++ Core Guidelines.