50 lines · plain
1.. title:: clang-tidy - bugprone-capturing-this-in-member-variable2 3bugprone-capturing-this-in-member-variable4==========================================5 6Finds lambda captures that capture the ``this`` pointer and store it as class7members without handle the copy and move constructors and the assignments.8 9Capture this in a lambda and store it as a class member is dangerous because10the lambda can outlive the object it captures. Especially when the object is11copied or moved, the captured ``this`` pointer will be implicitly propagated12to the new object. Most of the time, people will believe that the captured13``this`` pointer points to the new object, which will lead to bugs.14 15.. code-block:: c++16 17 struct C {18 C() : Captured([this]() -> C const * { return this; }) {}19 std::function<C const *()> Captured;20 };21 22 void foo() {23 C v1{};24 C v2 = v1; // v2.Captured capture v1's 'this' pointer25 assert(v2.Captured() == v1.Captured()); // v2.Captured capture v1's 'this' pointer26 assert(v2.Captured() == &v2); // assertion failed.27 }28 29Possible fixes:30 - marking copy and move constructors and assignment operators deleted.31 - using class member method instead of class member variable with function32 object types.33 - passing ``this`` pointer as parameter.34 35Options36-------37 38.. option:: FunctionWrapperTypes39 40 A semicolon-separated list of names of types. Used to specify function41 wrapper that can hold lambda expressions.42 Default is `::std::function;::std::move_only_function;::boost::function`.43 44.. option:: BindFunctions45 46 A semicolon-separated list of fully qualified names of functions that can47 capture ``this`` pointer.48 Default is `::std::bind;::boost::bind;::std::bind_front;::std::bind_back;49 ::boost::compat::bind_front;::boost::compat::bind_back`.50