Alex Rivera | Logout

resize versus push_back in std::vector : does it avoid an unnecessary copy assignment?

Asked 2009-12-14T19:03:39.157
26

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?

Edit
Report

1 Answer

8

At EA (Electronic Arts) this was considered such a big problem that they wrote their own version of the STL, EASTL, which among many other things include a push_back(void) in their vector class.

answered 2009-12-14T19:44:57.260

Your Answer