Skip to main content
GameDev.net gamedev.net
🔒 Locked

vector reallocation

Started by AnthonyB Mar 25, 2012 at 1:18 AM 1 replies 950+ views
Original Post
AnthonyB
AnthonyB
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.
SiCrane
SiCrane
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.
AnthonyB
AnthonyB
That makes sense. I was blindly ignoring the fact that some classes may not have move constructors. Thanks.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.