I was wondering what happens with the capacity of a container like a vector or a string when you copy it. I ran the following experiment (Clang 8) not knowing exactly what to expect.
#include <iostream>
#include <vector>
#include <string>
int main()
{
using namespace std;
vector<int> v;
v.reserve(100);
vector<int> v2 = v;
cout << v2.capacity() << endl;
// 0
string s;
s.reserve(100);
string s2 = s;
cout << s2.capacity() << endl;
// 15
return 0;
}
So it looks like capacity is not copied. That seems reasonable on the one hand, because it would be wasteful to make the copies take more memory than necessary. But, on the other hand, I might have expected the copies to have the same capacity. Maybe I did want to make several vectors with some preallocated capacity. More generally, I usually expect copies to behave similarly to the copied object, put coarsely, to return the same results when const
methods are called. I know there is no such rule and there are surely many cases in the standard where this does not happen. But in any case, I would like to know if there are any specifications about it, if the standard explicitly says that the capacity of a container does not need to be maintained across copies. Ideally, I would like to get some specific behavior, e.g. assuming that what clang does is correct (not maintaining the capacity), then I would like to take for granted that capacity is never going to be maintained (e.g. something like "capacity of the copy is what you would get after shrink_to_fit
"), although I imagine the standard would leave that up to the compiler.