+ 1
Why 3 destructor calls with 2 constructor calls
Hi Refer code below: It has two constructor calls and I am ok with it. Reserve along with emplace back avoids unnecessary copies . Why additional destructor call ? I was expecting only two destructor calls. Also, why pop back calls destructor ? Should not destructor be called when we shrink size to free vector memory ? https://sololearn.com/compiler-playground/cshNgFle7px1/?ref=app
7 Respuestas
+ 1
Basically, moving, copying and deleting stuff side effects...
Also not using shrink_to_fit unless necessary and allocating enough capacity might be better for performance. It's good to always leave extra reserve space in vectors.
comment out the shrink_to_fit part and your code behaves more like you would expect. shrink_to_fit is not without side effects.
some nice links:
https://frogatto.com/2009/11/17/how-cs-vector-works-the-gritty-details/
also
https://www.cppstories.com/2014/05/vector-of-objects-vs-vector-of-pointers/
+ 1
Now I feel why three destructors. Additional destructor is called due to shrink to fit. Shrink to fit asks for vector element copy as size changes from 2 to 1
+ 1
yes, so use shrink_to_fit only if it is necessary to keep the vector at a certain size.Normally, it's better to avoid using it.
https://stackoverflow.com/questions/23502291/is-shrink-to-fit-the-proper-way-of-reducing-the-capacity-a-stdvector-to-its
+ 1
My bad. Popping back item is responsible to call destructor. Memory is no longer utilised by element and hence released, but it is still with vector which it may use for another element allocation. To release memory from vector scope and return it back to os, shrink to fit is needed , but it will again reallocate all remaining elements to new space needing copy constructor.
Yes, hence shrink to fit gives back memory to operating system (os), but it is costly operation as new allocation with smaller size calls for heavy copy constructor.
Thanks Bob_Li as always for helping
0
I had put the shrink to fit to verify when element is destructed.
Basically, it should not be destructed when done poped back. It should be deatructed when shrink to fit or clear is called.
Is this correct?
0
Thanks Bob_Li.
Basically destructor not called when pop_back is called. In other words, vector element is still present in memoty and not destroyed even though it was popped back.
Is this right?
In other words, vector elements are destroyed only if
1. Shrink to fit used after pop back
Or
2. Clear used on vector
Or
3. Vector object scope is over.
Is my understanding correct?
0
yes. unneccesry shrink_to_fit and clear only adds extra work. if you popped an item, it is already not accessible by the vector.