简体   繁体   中英

Does std::vector::assign/std::vector::operator=(const&) guarantee to reuse the buffer in `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?

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM