how does vector work?

Currently, I am finding a bug related to meory allocated by vector. I have some findings about the mechanism of vector.

0. vector maintains 3 pointers: _M_start, _M_finish, and _M_end_of_storage. At first, vector is empty, i.e. _M_start= _M_finish= _M_end_of_storage=NULL.

invariant: elements are stored in [_M_start, _M_finish), while its storage/capacity is [_M_start, _M_end_of_storage).

1. A vector allocates a large number of memory, n*sizeof(Obj), by calling reserve(n). If its capacity, (char*)_M_end_of_storage-(char*)_M_start,  is less than n*sizeof(Obj), it will malloc another memory, and copy data before free its original storage.

2. Vector's iterator: a pointer in c++

vector's begin() points to _M_start; vector's end() points to _M_finish.

3.Vector's capacity is equal to (char*)_M_end_of_storage - (char*)_M_start

4. Vector's clear call destructor on each elements in [_M_start, _M_finish), not free memory at all.

5. ~Vector() frees memory by calling ~_Vector_base().

 

For more info, please refer to /usr/include/c++/4.1.2/bits/stl_vector.h

你可能感兴趣的:(vector)