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