Why clear() used on vector of vectors doesn't

2019-10-08 09:29发布

问题:

I was so sure that vector calls the destructors of the contained objects that I just used the clear() on the main vector and then I reused the vector and the values of the vectors stored in it were not cleared...

EDIT - code:

vector<vector<int> > flush1;
flush1.reserve(4);
for(int i = 0; i != 4; ++i) flush1[i].reserve(7);
flush1.clear();
flush1[0].push_back(some_int);
flush1[1].push_back(some_int);
flush1[2].push_back(some_int);
flush1[3].push_back(some_int);
cout the size from flush1[0-3];
flush1.clear();

and again

flush1[0].push_back(some_int);
flush1[1].push_back(some_int);
flush1[2].push_back(some_int);
flush1[3].push_back(some_int);

and cout-ing the size from flush1[0-3] cout-s their previous size + new sizes (addition of old and new)

回答1:

The vector object has three pointers: the beginning, the end and end-of-reserved-storage.

The clear() method calls the destructor on each contained object and then sets the end pointer to the beginning.

So the data of the destructed objects will still be visible (using a debugger for example) in the reserved storage.