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);
lambda函数被保存为成员struct_variable.f
(也是类型std::function
),在回调中,struct_variable.f
在使用完捕获的变量后被替换为 another_compatible_std_function
。
这种做法能保证安全吗?
最佳答案
lambda 的代码部分被编译成机器代码,并且在赋值期间,仅分配指向该代码的函数指针。因此,只要您不再使用捕获的变量,重新分配保存 lambda 的变量应该是安全的,因为不会更改正在运行的代码。
关于c++ - 调用时为 std::function 分配新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40938118/