std::vector capacity after copying

  • Does vector::operator= change vector capacity? If so, how?
  • Does vector's copy constructor copy capacity?

I looked through documentation but could not find a specific answer. Is it implementation dependent?


Solution 1:

All you're guaranteed is that:

  1. The vector has enough capacity to store its elements. (Obviously.)
  2. The vector won't get a new capacity until it's current capacity is full.*

So how much extra or little an implementation wants to put is up to the implementation. I think most will make capacity match size, when copying, but it cannot lower capacity. (Because of number 2 above; reallocating while there's enough room is not allowed.)

* Mostly. See Charles' comments below.

Solution 2:

Does vector::operator= change vector capacity? If so, how?

It might change capacity. This happens only if the previous capacity was too small to hold the new size. If so, the new capacity is at least equal to the new size, but could be a larger value.

Does copy constructor copy capacity?

Per Table 65 Container requirements in C++03, X u (a); and X u = a; are both equivalent to X u; u = a;. This makes the copy ctor identical to the op= case, after default constructing the vector.