+ 4

c++ vector (destructor of objects problem)

I want to know why dtor is called 6 times after the push_back line (before last cout). Can anyone explain, thanks. https://code.sololearn.com/cOKPD7cSH2ah/?ref=app

19th Sep 2018, 5:41 PM
. �
.                                                � - avatar
2 Réponses
+ 6
It is happening due to vector reallocation. Vector was allocated in constructor with space for 5 elements. There is no space for element #6. In such situation vector allocates new storage with increased size (with some multiplier, like 2x), copies elements to the new storage, destroes elements at the old storage and finally deallocate it. Each vector resizing operation can cause reallocation and is the reason of broken iterators, pointers, references to the elements.
19th Sep 2018, 6:23 PM
Sergey Ushakov
Sergey Ushakov - avatar
3rd Oct 2018, 6:58 PM
wave rider
wave rider - avatar