c++ - 即使根据容量()仍有未使用的空间,std::vector 能否将其数据移动到 emplace_back()处的另一个地址?

标签 c++ c++11 vector language-lawyer

是否保证 std::vector 仅在 size()==capacity() 并调用 push_back() 时移动其数据或 emplace_back() 或者它也可以这样做吗?

最佳答案

规范有点间接。 容量指定为:

size_type capacity() const noexcept;

Returns: The total number of elements that the vector can hold without requiring reallocation.

第二部分来自reserve:

reserve(size_type n);

Remarks: Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().

由此可以得出结论,如果大小小于容量,则插入不会导致重新分配。

如果有空闲容量并且您没有显式调用 reserve,则没有单一直接声明 vector 不会重新分配。但是,[container.requirements.general]中有一个通用的容器要求:

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.

最后,我们来描述一下插入的效果:

[insert/emplace_back/push_back:]

Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid.

综上所述:除非另有说明,否则调用成员函数不会使迭代器无效。重新分配使迭代器无效(如上面 reserve 的一部分所述),因此除非另有说明,否则调用成员函数,特别是插入,不会重新分配,为这种情况提供了一个这样的覆盖规范其中新大小超过当前容量。

关于c++ - 即使根据容量()仍有未使用的空间,std::vector 能否将其数据移动到 emplace_back()处的另一个地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37571737/

相关文章:

具有默认模板参数的 C++14 变量模板?

c++ - 递归中意外的 std::bad_function_call

C++ vector 按值 : did I get it right? 传递

c++ - std::vector push_back 在并行 for 循环中使用时失败

c++ - 为什么用三元运算符来定义宏中的 1 和 0?

交替for循环的c++通用解决方案

c++ - 是否有一种算法可以在排序数组中搜索不包括一个复杂度为 O(lgn) 的指定数字的元素?

c++ - 资源管理- vector 和指针

c++ - Linux C++ ._MyFirst ._MyLast vector 等效

vector - 为什么通过替换默认值填充 Vec 比填充具有预设容量的东西快得多?