gpt4 book ai didi

c++ - std::vector::assign/std::vector::operator=(const&) 是否保证重用 `this` 中的缓冲区?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:29 25 4
gpt4 key购买 nike

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

下面的例子证明我可以,但是,标准保证吗?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;
}

Live example .

更新:This answer 提到

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

相当于

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

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

最佳答案

简答

没有。

不要那么简短的回答

该标准没有手动定义对vector 的这些操作。它仅将它们定义为容器的要求。 [vector]

A vector satisfies all of the requirements of a container and of a reversible container (given in two tables in [container.requirements]), of a sequence container, including most of the optional sequence container requirements ([sequence.reqmts]), of an allocator-aware container (Table 67), and, for an element type other than bool, of a contiguous container. The exceptions are the push_­front, pop_­front, and emplace_­front member functions, which are not provided. Descriptions are provided here only for operations on vector that are not described in one of these tables or for operations where there is additional semantic information.

唯一提到这些操作的地方是Container requirementsSequence container requirements .没有任何证据支持您的假设。

关于c++ - std::vector::assign/std::vector::operator=(const&) 是否保证重用 `this` 中的缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51892382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com