【问题标题】:Assign new value to std::function while calling调用时为 std::function 分配新值
【发布时间】:2016-12-02 17:46:38
【问题描述】:
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.fanother_compatible_std_function 替换。

这种做法能保证安全吗?

【问题讨论】:

  • 我想说是的,只要你小心点,因为这种情况类似于delete-在执行其成员函数之一期间对对象执行操作。但这很难从标准中证明。

标签: c++ lambda


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多