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

拈花ヽ惹草 提交于 2019-12-07 02:47:15

问题


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?

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;
}

Live example.

Update: This answer mentions that

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

is equivalent to

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

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


回答1:


Short answer

No.

Not so short answer

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

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.

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



来源:https://stackoverflow.com/questions/51892382/does-stdvectorassign-stdvectoroperator-const-guarantee-to-reuse-the-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!