调用时为std :: function赋值

时间:2016-12-02 17:46:38

标签: c++ lambda

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替换

这种做法是否保证安全?

1 个答案:

答案 0 :(得分:0)

lambda的代码部分被编译成机器代码,在分配期间,只指向指向该代码的指向函数的指针。因此,只要您不再使用捕获的变量,重新分配保存lambda的变量应该是安全的,因为不会更改正在运行的代码。

相关问题