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

c – 在调用过程中删除std :: function

发布时间:2020-12-16 03:39:05 所属栏目:百科 来源:网络整理
导读:在调用过程中,是否要销毁/删除std :: function是未定义的行为? class Event { public: Event(std::functionvoid() f) : func(std::move(f)) {} ~Event() {} std::functionvoid() func;};int main(){ std::vectorEvent events; auto func = []() { events.po
在调用过程中,是否要销毁/删除std :: function是未定义的行为?
class Event {
  public:
    Event(std::function<void()> f) : func(std::move(f)) {}
    ~Event() {}
    std::function<void()> func;
};

int main()
{
    std::vector<Event> events;
    auto func = [&]() {
      events.pop_back();  
      std::cout << "event" << std::endl;
      // do more work  
    };

    events.emplace_back(std::move(func));
    events[0].func();

    return 0;
}

解决方法

这是 [res.on.objects]p2未定义的:

If an object of a standard library type is accessed,and the beginning
of the object’s lifetime does not happen before the access,or the
access does not happen before the end of the object’s lifetime,the
behavior is undefined unless otherwise specified.

在这种情况下,“访问”包括对std :: function的函数调用操作符的调用. std :: function对象的生命周期在pop_back()调用结束时,在访问过程中结束.因此,访问不会在对象生命周期结束之前发生,并且行为未定义.

(编辑:李大同)

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

    推荐文章
      热点阅读