在调用过程中,是否要销毁/删除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未定义的:
@H_403_9@If an object of a standard library type is accessed,and the beginning@H_403_9@在这种情况下,“访问”包括对std :: function的函数调用操作符的调用. std :: function对象的生命周期在pop_back()调用结束时,在访问过程中结束.因此,访问不会在对象生命周期结束之前发生,并且行为未定义.
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.