调用时为 std::function 分配新值

Assign new value to std::function while calling

本文关键字:function 新值 分配 std 调用      更新时间:2023-10-16
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 的变量应该是安全的,因为不会更改任何运行代码。