微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

调用过程中,是否要销毁/删除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()调用结束时,在访问过程中结束.因此,访问不会在对象生命周期结束之前发生,并且行为未定义.

原文地址:https://www.jb51.cc/c/110810.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐