std::vector 元素的销毁顺序

2023-06-05C/C++开发问题
0

本文介绍了std::vector 元素的销毁顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

可能的重复:
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.

这篇关于std::vector 元素的销毁顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6