2019-07-12
Does std::vector have to resize if the elements it contains grow in size?
stackoverflow
Question

I apologize if this is too basic a question to ask here; I've been reading a bit about std::vector and I understand that it has to resize when the size reaches capacity. This can be an expensive operation if the objects it contains are large since it has to copy every one of them.

My question is: how does std::vector handle the actual size of the objects it contains growing? Suppose I initialize some

std::vector<Obj> vec(100);

And each Obj is initialized to something very small. But what if I then do something like

vec[14].ENGORGIO()

So that it now takes much more memory. Since the elements of std::vector are stored in contiguous memory, does this mean that it has to resize (expensively!)

To avoid this kind of thing, should I instead be storing pointers in a vector rather than the objects themselves? Like so

std::vector< std::unique_ptr<Obj> > vec;

Thank you

Answer
1

The size of a data type in C++ is set at compile time and cannot change. The data type may contain references to other objects, and these other objects can vary in size, but the size of the reference, and thus the data type, is unchanging.

Consider a vector of vectors. The inner vector may contain 0 elements or billions and billions and it will always be the same size. The outer vector only knows that it contains 0 or more vectors and knows nothing about what is contained inside the inner vectors.

You do not have to worry about this.

Does std::vector have to resize if the elements it contains grow in size?
See more ...