Closed Quick-One closed 2 weeks ago
Looks like you are expecting existing elements to be moved before constructing the new element on reallocation. I think the current implementation has to do with making code like a.emplace_back(a[0])
work correctly. If the argument of emplace_back refers to an element in the vector, when a reallocation happens, if the existing elements are moved to the new array first (before constructing the new element), then the new element would be constructed from a moved-from object.
I think the current implementation has to do with making code like
a.emplace_back(a[0])
work correctly.
Yeah. Perhaps this is required by the standard, see [sequence.reqmts]/21 Note 1.
That makes sense. That answers my question, thanks a lot.
This program gives the following output:
During the second emplace_back call, the array is reallocated as the previous capacity was 1. The output seems to demonstrate that the new element is first constructed and then the existing elements are moved to the newly reallocated array. The former is a random write while the latter is a sequential write.
Wouldn't it be ideal to reverse the order of these operations to ensure all operations are sequential writes?
Similar behaviour is shown by push_back with the exception of having an extra move operation.