std::vector 中的项是动态分配的,并且在重新分配时它们的地址可能会发生变化。因此,不可能依赖它们的地址,因为它不稳定。
另一方面,如果我有一个包含一些项目的 std::vector
并且我无意在其生命周期中更改它的任何内容,那么它是否有效(嗯-定义)来使用其项目的地址?
示例:
std::vector<foo> foos;
foos.reserve(100);
for(size_t i=0;i<100;++i){
foos.emplace_back(make_random_foo());
}
//From now no one can touch foos
auto ptr_to_the_fifth_foo=&foos[4];
换句话说,标准是否保证注释会影响 vector 项地址,因为我自己没有这样做?
最佳答案
如果没有调用std::vector
的成员函数,则 vector 可能根本不会改变,因此内容保持不变并且所有指针保持有效。
在您的示例中,您调用 operator[](size_type n)
,它在标准中定义为相当于 *(a.begin() + n)
。
std::vector
是一个容器,因此,容器要求保存以下状态:
Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container.
由于未指定 begin()
来使容器的任何迭代器无效,因此 operator[]
也不会。
关于c++ - 使用稳定 vector 中项目的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36115191/