Reputation: 2295
Say you are implementing a function that receives a reference to a vector that is to be filled:
func(std::vector <T> & vec) { ...
Now, the function is going to resize and fill this vector, but we don't really know what the vector had inside it previously, or what it's capacity was. To be really safe, one could write:
vec.clear();
vec.resize(...);
vec.shrink_to_fit();
Is this really necessary, or is there a better way to do this?
Upvotes: 2
Views: 1085
Reputation: 21803
So long as you will overwrite every element (or don't mind untouched elements being garbage), you don't need to clear the vector before resizing. The exception is if you want to fill the whole vector with a default value provided to resize, in which case you do need to clear it.
Usually you pass the vector by reference to save memory allocations by taking advantage of the existing reserved capacity. Using shrink_to_fit
defeats that purpose, as the vector capacity can go up and down (if the compiler does anything for a shrink). If you want to minimize memory, return a fresh vector by value.
Upvotes: 3
Reputation: 5741
implementing a function that receives a reference to a vector that is to be filled
There is no difference between the logic which you can write inside the func and inside the function where std::vector has actually created and passed as reference to func. Both are fundamentally the same and safe.
Upvotes: 0
Reputation: 8824
If you do not care about the previous content, just return by value, you will have copy elision on new variable and move semantics otherelse.
std::vector <T> func();
// later
auto vec = func(); // will use copy elision and Return Value Optimisation
existingVec = func(); // move semantic, previous content will be released and new one will be steal from the temporary
If you care about the previous content, or at least wants to prevent a dynamic allocation if the previous array capacity is enough, resize
should be enough
Upvotes: 1