90 lines · plain
1.. title:: clang-tidy - modernize-avoid-bind2 3modernize-avoid-bind4====================5 6The check finds uses of ``std::bind`` and ``boost::bind`` and replaces them7with lambdas. Lambdas will use value-capture unless reference capture is8explicitly requested with ``std::ref`` or ``boost::ref``.9 10It supports arbitrary callables including member functions, function objects,11and free functions, and all variations thereof. Anything that you can pass12to the first argument of ``bind`` should be diagnosable. Currently, the only13known case where a fix-it is unsupported is when the same placeholder is14specified multiple times in the parameter list.15 16Given:17 18.. code-block:: c++19 20 int add(int x, int y) { return x + y; }21 22Then:23 24.. code-block:: c++25 26 void f() {27 int x = 2;28 auto clj = std::bind(add, x, _1);29 }30 31is replaced by:32 33.. code-block:: c++34 35 void f() {36 int x = 2;37 auto clj = [=](auto && arg1) { return add(x, arg1); };38 }39 40``std::bind`` can be hard to read and can result in larger object files and41binaries due to type information that will not be produced by equivalent42lambdas.43 44Options45-------46 47.. option:: PermissiveParameterList48 49 If the option is set to `true`, the check will append ``auto&&...`` to the end50 of every placeholder parameter list. Without this, it is possible for a fix-it51 to perform an incorrect transformation in the case where the result of the ``bind``52 is used in the context of a type erased functor such as ``std::function`` which53 allows mismatched arguments. Default is is `false`.54 55For example:56 57.. code-block:: c++58 59 int add(int x, int y) { return x + y; }60 int foo() {61 std::function<int(int,int)> ignore_args = std::bind(add, 2, 2);62 return ignore_args(3, 3);63 }64 65is valid code, and returns `4`. The actual values passed to ``ignore_args`` are66simply ignored. Without ``PermissiveParameterList``, this would be transformed into67 68.. code-block:: c++69 70 int add(int x, int y) { return x + y; }71 int foo() {72 std::function<int(int,int)> ignore_args = [] { return add(2, 2); }73 return ignore_args(3, 3);74 }75 76which will *not* compile, since the lambda does not contain an ``operator()``77that accepts 2 arguments. With permissive parameter list, it instead generates78 79.. code-block:: c++80 81 int add(int x, int y) { return x + y; }82 int foo() {83 std::function<int(int,int)> ignore_args = [](auto&&...) { return add(2, 2); }84 return ignore_args(3, 3);85 }86 87which is correct.88 89This check requires using C++14 or higher to run.90