28 Jun 2019

How does your vector grow?

How often is the destructor called below after populating a five element STL vector? Remarkably it’s 17 times. Run the code yourself.

How often is the destructor called below after populating a five element STL vector? Remarkably it’s 17 times. Run the code yourself.

g++ -std=c++2a main.cpp && ./a.out

For each push we call the default constructor to create a transient object and then call the copy constructor to populate the new element with its data. So far so good. But crucially when the vector is resized we must also copy all the existing elements into the new container, resulting in an unexpected growth. Not an issue for this simple case but what if the class were large? Additionally if there’s a bug in the copy constructor and pushing a new element exceeds the underlying vector capacity then we could be corrupting existing valid data just by quietly copying it around.