c++ - 使用稳定 vector 中项目的地址

标签 c++ c++11 vector

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/

相关文章:

android - 未找到 int com.example.nimashahbazi.mooshak.EncryptingActivity.encrypt 的实现

c++ - Const 关键字用法 C++

c++ - boost::range_iterator 和 boost::iterator_range 混淆

c++ - 如何使 C++ 类生成不可克隆的对象

c++ - typedef中synonym的含义

r - 通过给定的值分布创建向量

c++ - 3维 vector 的交集/可行性控制

c++ - 如何将一系列形状缩小一半?

c++ - 有关清理此终止条件的建议

c++ - 为什么这个语法无效? vector 指针->[0]