Assign a new value to the std :: function

int i = 9;
struct_variable.f = [i](T struct_variable&) {
   do_something_with_capture_variable(i);
   ...
   struct_variable.f = another_compatible_std_function;
   //do something else, but never use captured variable after here
   ...
};

struct_variable.f(struct_variable);

The lambda function is saved as a member struct_variable.f(which is also introduced std::function), and in the callback it struct_variable.fis replaced by another_compatible_std_functionafter the use of the captured variable is completed.

How safe is this practice?

+4
source share
1 answer

Part of the lambda code is compiled into machine code, and when assigned, only a pointer to a function is assigned, indicating that this code is assigned. Thus, until you no longer use the captured variables, it should be safe to reassign the variable containing the lambda, because the current code will not be changed.

0
source

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


All Articles