What does it mean that lambda is static?

Let's say I have a binary search function that initializes and uses lambda:

bool const 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); } 

Not indicating that this is completely redundant and just focuses on lambda; Is it expensive to declare and define this lambda object every time? Should it be static? What would mean that lambda is static?

+6
source share
2 answers

The variable 'comp' with type <some anonymous lambda class> can be made static, much like any other local variable, that is, the same variable pointing to the same memory address each time this function is run) .

However, be careful when using closures, which will lead to subtle errors (passing by value) or errors at runtime (pass-by-reference), since 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 here to introduce a variable that you might want to capture in your comparator, and the functionality that this "custom_binary_search" implements is probably not very useful.

+5
source

The following code compiles and works fine in visual studio 2013:

 bool const test(int & value) { //edit `&value` into `&` @log0 static auto comp = [&](int const a, int const b) { return a < (b + value); }; return comp(2,1); } 

And later:

 int q = 1; cout << test(q); // prints 0 //OK q++; cout << test(q); // prints 1 //OK 

The compiler converts any lambda declaration into a regular function, and this is done at compile time. The actual definition in the test function is simply the regular assignment of the comp variable with a pointer to the c function. Closing is common, but will only work to the extent that they have been determined. In any other area, they will fail or create a memory corruption error.

The definition of static comp only slightly improve performance or not at all.

Hope this helps: Razvan.

0
source

Source: https://habr.com/ru/post/955965/


All Articles