49 lines · plain
1.. title:: clang-tidy - cppcoreguidelines-misleading-capture-default-by-value2 3cppcoreguidelines-misleading-capture-default-by-value4=====================================================5 6Warns when lambda specify a by-value capture default and capture ``this``.7 8By-value capture defaults in member functions can be misleading about whether9data members are captured by value or reference. This occurs because specifying10the capture default ``[=]`` actually captures the ``this`` pointer by value,11not the data members themselves. As a result, data members are still indirectly12accessed via the captured ``this`` pointer, which essentially means they are13being accessed by reference. Therefore, even when using ``[=]``, data members14are effectively captured by reference, which might not align with the user's15expectations.16 17Examples: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 132 }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 143 }44 };45 46This check implements `F.5447<https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#f54-when-writing-a-lambda-that-captures-this-or-any-class-data-member-dont-use--default-capture>`_48from the C++ Core Guidelines.49