Isn't std::vector usually implemented to avoid copying whenever possible? Judging by what I am reading -- no. Yet the overhead involved in the checks necessary seems like it would be trivial.
Printable View
Isn't std::vector usually implemented to avoid copying whenever possible? Judging by what I am reading -- no. Yet the overhead involved in the checks necessary seems like it would be trivial.
Yes and no. I doubt it is so low level that it is able to do the equivalent of a realloc when it needs more space. However, it attempts to minimize reallocations and is generally pretty efficient at it.
In addition, the new standard will allow move semantics which would have the potential to make reallocations even less expensive.
Peculiarly enough, I've just scoured both the C++98 and the C++09 drafts and cannot find any mention of the allocation complexity of repeated inserts or push_backs for vectors. In other words, as far as I can see it's legal for a vector to just reallocate for a single additional element every time push_back is called. The only place where a reallocation complexity is specified is for the range constructor (two iterators), which says that, if the iterators are input iterators, the operation will take at most order of log(N) reallocations, where N is distance(first, last). In other words, this constructor requires increments of a constant factor > 1.
I must be wrong about this. I'm absolutely sure this is required for other operations, too, but I just can't find the place.
>> I'm absolutely sure this is required for other operations, too
I've never heard that. I've always been under the impression that a naive "always increase capacity by one" implementation was perfectly standard.
The standard says that push_back would be an equivalent of insert(end(), x). It also says:
Now, if you were to copy things around for each push_back, that wouldn't be constant time insert at the end. It would be linear time.Quote:
In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time.
That's it exactly. It wouldn't state the method used to achieve amortised constant time push_back, as they tend to like to leave that to the implementation details. But then there's probably only one way to achieve it anyway. So I guess growing by size multiplication instead of addition is implied.
Well, back to the original topic, one can easily write their own container that uses VirtualAlloc and Placement new etc, but why bother! Profile first!