std::vector::assign/std::vector::operator=(const&) 是否保证在"this"中重用缓冲区?

Does std::vector::assign/std::vector::operator=(const&) guarantee to reuse the buffer in `this`?

本文关键字:std vector this 缓冲区 operator assign 是否 const      更新时间:2023-10-16

如果我将一个向量分配或复制到另一个向量(其容量与前者的大小相同或更大(,我可以假设后者的缓冲区将被重用吗?

下面的示例演示我可以,但是,它是否由标准保证? 在这方面,std::vector::assignstd::vector::operator=的行为有什么区别吗?

#include <vector>
#include <iostream>
#include <cassert>
int main()
{
std::vector a {1, 2, 3, 4, 5};
std::vector b {1, 2, 3, 4};
std::vector c {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "1 ==== " << a.capacity() << " " << a.data() << std::endl;
const auto* pa = a.data();   
a = b;
assert(pa == a.data());
std::cout << "2 ==== " << a.capacity() << " " << a.data() << std::endl;
a = c;
assert(pa != a.data());
std::cout << "3 ==== " << a.capacity() << " " << a.data() << std::endl;
}

活生生的例子。

更新:这个答案提到

void assign(size_type n, const T& t);

相当于

erase(begin(), end());
insert(begin(), n, t);

标准真的是这样制定的吗,它是否适用于所有std::vector::assign过载?

简答

不。

不是那么简短的答案

标准不会在vector上手动定义这些操作。它仅将它们定义为容器的要求。[矢量] 说

向量满足容器和可逆容器(在 [container.requirements] 中的两个表中给出(、序列容器(包括大多数可选序列容器要求 ([sequence.reqmts](、分配器感知容器(表 67(以及连续容器(对于 bool 以外的元素类型(的所有要求。例外情况是未提供的 push_front、pop_front 和emplace_front成员函数。此处仅针对这些表中未描述的向量操作或存在其他语义信息的操作提供说明。

唯一提到这些操作的地方是容器要求和序列容器要求。没有什么支持你的假设。