C & C++

C & C++

Made by DeepSource

Found usage of std::bind in place of lambda expression CXX-W2064

Anti-pattern
Minor

There are concerns related to std::bind which are addressed by lambda expression as mentioned below

  • std::bind can make the code harder to understand and maintain. It requires additional syntax and can be less intuitive compared to lambda expressions.

  • std::bind can result in larger object files and binaries due to the type information that will not be produced by equivalent lambdas.

Replace the usage of std::bind with lambda expressions. Lambda expressions provide a more concise and expressive way to bind arguments to a function call.

Bad practice

#include <functional>


int add(int x, int y) { return x + y; }

void foo(int a, int b) {
  // Using std::bind
  const int val_ten = 10;
  auto plus_ten = std::bind(add, val_ten, _1);

  // Call the bound function
  plus_ten(3);
}

Recommended

void foo(int a, int b) {
  // Using lambda expression
  int val_ten = 2;
  auto plus_ten = [=](auto && arg1) { return add(val_ten, arg1); };


  // Call the lambda
  plus_ten(3);
}

References: - cppreference.com - std::bind