std::vector 元素的销毁顺序

2021-12-21 00:00:00 destructor vector c++

可能的重复:
STL容器元素销毁顺序

有没有保证 std::vector 的元素会从最后到第一个销毁?

Is there a guarantee the the elements of an std::vector would be destroyed from last to first?

推荐答案

2003:5.3.5/6 关于 delete[] 的说明:

2003:5.3.5/6 says about delete[]:

delete 表达式将调用要删除的对象或数组元素的析构函数(如果有).在数组的情况下,元素将按照地址递减的顺序销毁(即,按照其构造函数完成的相反顺序;参见 12.6.2).

The delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).

因此,如果您的 std::vector 对象的分配器使用 delete[] 那么,是的,它必然会以相反的顺序销毁元素.

So if your std::vector object's allocator uses delete[] then, yes, it is bound to destroy elements in reverse order.

但是,不能保证您的 std::vector 会以这种方式工作(事实上,它很可能不会),而且我找不到任何特定于容器.

However, there is no guarantee that your std::vector will work this way (and, in fact, it most likely does not), and I can't find any citations specific to the container.

真的,我认为这完全取决于您的分配器,而 2003:20.1.5(列出了对分配器的要求)似乎对此没有任何说明.

Really, I think it's all down to your allocator and 2003:20.1.5 (which lists the requirements placed upon allocators) doesn't appear to say anything about it.

相关文章