Search code examples
c++stdvectorc++03

Can I insert a vector to itself with std::vector::insert?


Is it allowed by the C++03 standard to append a std::vector to itself? I wonder if the source iterators can become invalid if v needs to reallocate memory. In my STL implementation, the old memory is kept until the new memory has been created. But can I rely on this? If not, is v.reserve(2 * v.size()) before the insert a good solution to avoid the reallocation altogether?

vector<int> v;
v.reserve(3);
v.push_back(1);
v.push_back(2);
v.push_back(3);
// v may need to reallocate because its capacity may be less than 6.
// Is this operation safe?
v.insert(v.end(), v.cbegin(), v.cend());

or

// Here v will _not_ need to reallocate because it has enough capacity.
// Is this operation safe?
v.reserve(2 * v.size());
v.insert(v.end(), v.cbegin(), v.cend());

Solution

  • Regardless of whether perform reserve in advance or not, the behavior is undefined. For std::vector::insert:

    inserts elements from range [first, last) before pos.

    The behavior is undefined if first and last are iterators into *this.