However, if array is a vector, this won’t happen, because the memory will be deallocated as soon as array goes out of scope (regardless of whether the function exits early or not).
This makes std::vector much safer to use than doing your own memory allocation.
This may or may not be be overkill depending on whether this code is proven to be a performance bottleneck.
In conclusion, to insert several elements into a container, use the container methods whenever you can.
Lavavej, you want to make the most of this piece of feedback.
Here I want to flesh out one these pieces of advice that he gave.
This is not only handy (as you don’t have to do it yourself), it also helps prevent memory leaks.
Consider the following snippet: If early Exit is set to true, array will never be deallocated, and the memory will be leaked.
First, when we resized the array, the existing element values were preserved!
Second, new elements are initialized to the default value for the type (which is 0 for integers).