假设 STL 向量存储始终是连续的是否安全?
如果您有一个已调整大小的 STL 向量,那么获取元素 0 的地址并假设向量的其余部分将跟随在内存中是否安全?
例如
vector<char> vc(100);
// do some stuff with vc
vc.resize(200);
char* p = &vc[0];
// do stuff with *p
If you have an STL vector which has been resized, is it safe to take the address of element 0 and assume the rest of the vector will follow in memory?
e.g.
vector<char> vc(100);
// do some stuff with vc
vc.resize(200);
char* p = &vc[0];
// do stuff with *p
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,这是一个有效的假设 (*)。
来自 C++03 标准 (23.2.4.1):
(*) ...但要注意向数组添加元素后重新分配的数组(使任何指针和迭代器无效)。
Yes, that is a valid assumption (*).
From the C++03 standard (23.2.4.1):
(*) ... but watch out for the array being reallocated (invalidating any pointers and iterators) after adding elements to it.
C++03 标准添加了措辞以明确向量元素必须是连续的。
C++03 23.2.4 第 1 段包含以下 C++98 标准文档中未的语言:
Herb Sutter 在他的一篇博客文章中谈到了这一变化,不要畏缩:向量保证是连续的:
The C++03 standard added wording to make it clear that vector elements must be contiguous.
C++03 23.2.4 Paragraph 1 contains the following language which is not in the C++98 standard document:
Herb Sutter talks about this change in one of his blog entries, Cringe not: Vectors are guaranteed to be contiguous:
存储始终是连续的,但它可能会随着向量容量的变化而移动。
如果在容量更改操作之前元素零(或任何元素)上有指针、引用或迭代器,则它会失效并且必须重新分配。
Storage is always contiguous, but it may move as the vector's capacity is changed.
If you had a pointer, reference, or iterator on element zero (or any element) before a capacity-changing operation, it is invalidated and must be reassigned.
是的,它是连续的
Yes it's contiguous
std::vector
保证项目存储在连续数组中,因此是数组的首选替代品,也可用于与平台相关的低级代码(如 Win32 API 调用)进行交互)。 要获取指向数组的指针,请使用:std::vector
guarantees that the items are stored in a contiguous array, and is therefore the preferred replacement of arrays and can also be used to interface with platform-dependent low-level code (like Win32 API calls). To get a pointer to the array use:是的。
它应该总是连续的
yes.
it should alway be contiguous