When invoking the method push_back from std::vector, its size is incremented by one, implying in the creation of a new instance, and then the parameter you pass will be copied into this recently created element, right? Example:
myVector.push_back(MyVectorElement());
Well then, if I want to increase the size of the vector with an element simply using its default values, wouldn’t it be better to use the resize method instead? I mean like this:
myVector.resize(myVector.size() + 1);
As far as I can see, this would accomplish exactly the same thing but would avoid the totally unnecessary assignment copy of the attributes of the element.
Is this reasoning correct or am I missing something?
At least with GCC, it doesn’t matter which you use (Results below). However, if you get to the point where you are having to worry about it, you should be using pointers or (even better) some form of smart pointers.. I would of course recommend the ones in the boost library.
If you wanted to know which was better to use in practice, I would suggest either
push_backorreserveas resize will resize the vector every time it is called unless it is the same size as the requested size.push_backand reserve will only resize the vector if needed. This is a good thing as if you want to resize the vector tosize+1, it may already be atsize+20, so calling resize would not provide any benefit.Test Code
Test Output