加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 调用时为std :: function赋值

发布时间:2020-12-16 06:52:55 所属栏目:百科 来源:网络整理
导读: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(st
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的变量应该是安全的,因为不会更改正在运行的代码.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读