c++ - 调用时为 std::function 分配新值

标签 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

这种做法能保证安全吗?

最佳答案

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

关于c++ - 调用时为 std::function 分配新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40938118/

相关文章:

c++ - 使用 OpenCV 通过直方图查找 HSV 阈值

c++ - 在 DirectX Windows 8 应用程序中播放声音

c++ - 使用 C++ 中的 "new"创建的指针进行内存管理

ruby - 为什么在 Ruby 中屈服于 lambda splat 数组参数?

c++ - clang++ 3.1 但在 Lion Xcode 4.3.3 上没有 `cxx_lambdas`

java - 如何在参数和结果之间链接 lambda 函数中的泛型

c++ - STL 容器 move 语义并按值返回 : how many times of copying get avoided away?

c++ - pthread_cond_wait() 没有等待,返回 int 6

multithreading - 在为 Runnable 提供 lambda 时,为什么我不必重写 run 方法?

Python 数据框使用带有 2 个变量的 lambda 函数和 if else 语句分配新列