What does it mean for a lambda to be static?
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.
the following code compiles and runs ok 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 will transform any lambda declaration into a regular function and this is done at compile time. The actual definition in the test
function is just a regular assignment to the comp
variable with the pointer to a c function.
Closures are the generaly the same but will work ok only in the scope they were defined. In any other scope they will fail or generate a memory corruption bug.
Defining comp
static would only improve the performance insignificantly or not at all.
Hope this helps: Razvan.