Is it safe to assume that STL vector storage is always contiguous?(假设 STL 向量存储总是连续的是否安全?)
问题描述
如果您有一个已调整大小的 STL 向量,那么获取元素 0 的地址并假设向量的其余部分将跟随在内存中是否安全?
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?
例如
vector<char> vc(100);
// do some stuff with vc
vc.resize(200);
char* p = &vc[0];
// do stuff with *p
推荐答案
是的,这是一个有效的假设 (*).
来自 C++03 标准 (23.2.4.1):
From the C++03 standard (23.2.4.1):
存储向量的元素连续,这意味着如果 v 是向量,其中 T 是一些类型不是 bool,那么它服从身份 &v[n] == &v[0] + n for所有 0 <= n
The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
(*) ...但要注意在向数组添加元素后重新分配数组(使任何指针和迭代器无效).
(*) ... but watch out for the array being reallocated (invalidating any pointers and iterators) after adding elements to it.
这篇关于假设 STL 向量存储总是连续的是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:假设 STL 向量存储总是连续的是否安全?


基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01