Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean for a lambda to be static?

Tags:

c++

lambda

Say I have a binary search function which initializes and uses a lambda:

bool custom_binary_search(std::vector<int> const& search_me)
{
  auto comp = [](int const a, int const b)
    {
      return a < b;
    };

  return std::binary_search(search_me.begin(), search_me.end(), comp);
}

Without pointing out that this is completely redundant and just focusing on the lambda; is it expensive to be declaring and defining that lambda object every time? Should it be static? What would it mean for a lambda to be static?

like image 862
quant Avatar asked Oct 15 '13 08:10

quant


People also ask

Can lambdas be Constexpr?

The C++17 version allowed the lambda expressions to be used in constant expressions. C++ lambda can be used in a constexpr or declared as a constexpr. If a lambda expression satisfies all the requirements of a constant expression, then it will be an implicit constexpr, even without specifying constexpr.

What is lambda in signals?

The lambda sensor, also called lambda probe, measures the level of oxygen in exhaust gases and it's placed on the engine exhaust.

Why is lambda so important?

AWS Lambda sparked the rise of serverless computing in the cloud, has changed our conception of “cloud-native” applications, and has become critical to Amazon's cloud strategy. AWS Lambda lets you run code without provisioning or managing servers, paying only for the compute time you consume.


1 Answers

The variable 'comp' with type <some anonymous lambda class> can be made static, pretty much as any other local variable, i.e. it is the same variable, pointing to the same memory address, every time this function is run).

However, beware of using closures, which will lead to subtle bugs (pass by value) or runtime errors (pass-by-reference) since the closure objects are also initialized only once:

bool const custom_binary_search(std::vector<int> const& search_me, int search_value, int max)
{
  static auto comp_only_initialized_the_first_time = [max](int const a, int const b)
  {
      return a < b && b < max;
  };

  auto max2 = max;
  static auto comp_error_after_first_time = [&max2](int const a, int const b)
  {
      return a < b && b < max2;
  };

  bool incorrectAfterFirstCall = std::binary_search(std::begin(search_me), std::end(search_me), search_value, comp_only_initialized_the_first_time);
  bool errorAfterFirstCall = std::binary_search(std::begin(search_me), std::end(search_me), search_value, comp_error_after_first_time);

  return false; // does it really matter at this point ?
}

Note that the 'max' parameter is just there to introduce a variable that you might want to capture in your comparator, and the functionality this "custom_binary_search" implements is probably not very useful.

like image 130
Martin J. Avatar answered Oct 11 '22 15:10

Martin J.