本文介绍了std :: vector :: assign/std :: vector :: operator =(const&)是否保证重用`this`中的缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I assign or copy one vector to another (that has the same or bigger capacity than the size of the former), can I assume that the buffer of the latter will be reused?

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

The following example demonstrates that I can, however, is it guaranteed by the standard?Is there any difference between behaviour of std::vector::assign and std::vector::operator= in this regard?

#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的所有重载?

Does the standard really formulate it this way and does it apply to all overloads of std::vector::assign?

推荐答案

简短答案

否.

标准未在vector上手动定义这些操作.它仅将它们定义为容器的要求. [vector]

The standard does not manually define these operations on vector. It only defines them as a requirement for containers. [vector] says

仅提及这些操作的地方是容器要求序列容器要求.没有任何证据支持您的假设.

The only places where these operation are mentioned are Container requirements and Sequence container requirements. Nothing supports your assumption.

这篇关于std :: vector :: assign/std :: vector :: operator =(const&amp;)是否保证重用`this`中的缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 10:39
查看更多