vector reallocation

Started by
1 comment, last by AnthonyB 12 years, 1 month ago
Out of curiosity, I've been looking into how std::vector works in detail. Something I've discovered has me completely baffled.

When a vector is reallocated as a result of growing in size beyond its capacity, it creates a new array, moves (Thanks to C++11 capabilities.) the data over, then deletes the old array. When the old array is deleted, all of the destructors are called for the classes in the array.

Considering the classes were just moved (not copied) to a new memory location, what purpose can calling the destructors serve? Even if these classes had dynamically allocated memory, the addresses of that memory are still retained, no copy of that memory has been made, so no leak can occur. I absolutely cannot think of any reason that the destructors need to be called in this scenario, and I'm hoping there's just something I'm ignorant of.

If you know why this is done, or have any theories, please share.
Advertisement
Not everything implements move constructors by transfer of ownership. When working with objects whose move constructors are the same as their copy constructors, usually by not explicitly implementing a move constructor, you still need to clean up via the destructor.
That makes sense. I was blindly ignoring the fact that some classes may not have move constructors. Thanks.

This topic is closed to new replies.

Advertisement