Does resizing an outer vector copies the inner vec

2019-07-08 06:05发布

问题:

Say you have a vector of vector:

vector<vector<string> > v;

when the internal array of the outer vector is resized (and suppose the internal array also have to be reallocated to a different address), for example by doing lots of v.push_back(), does the internal array of the inner vectors get copied as well (because vector's copy constructor usually copies the internal array), or does C++ have a way to resize the outer vector without copying everything recursively?

Does C++11 move constructor affect this? Does this depend on the STL implementation?

回答1:

Yes, in C++03, the inner vectors are copied when a reallocation is needed for the outer vector. In C++11, they are moved. It depends on the implementation only so far as the implementation being correct. If the implementation is correct, this is the behavior.



回答2:

Yes, if the storage used by the vector (the "outer" one) can't just be extended but it moves to a different address, then the data (no matter what that data is) in the vector have to be moved as well. That's the reason iterators for vectors should always be considered invalid after a e.g. push_back.



标签: c++ vector