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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...