Ferruccio Ferruccio - 7 days ago 6
C++ Question

Is it safe to assume that STL vector storage is always contiguous?

If you have an STL vector which has been resized, is it safe to take the address of element 0 and assume the rest of the vector will follow in memory?

e.g.

vector<char> vc(100);
// do some stuff with vc
vc.resize(200);
char* p = &vc[0];
// do stuff with *p

Answer

Yes, that is a valid assumption (*).

From the C++03 standard (23.2.4.1):

The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

(*) ... but watch out for the array being reallocated (invalidating any pointers and iterators) after adding elements to it.

Comments