+ 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
2 Answers
+ 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.
+ 1
Hi
Because of the hidden vector's little helper object
I had the same puzzle
See my code https://code.sololearn.com/c5uT43WSJ0f0/#cpp
and the thread here:
https://www.sololearn.com/Discuss/1514677/can-someone-explain-what-is-going-on-in-this-code-i-encounter-it-in-c-challenge-and-cant-understand
Cheers