STL: The Vector
devblogs.microsoft.com
devblogs.microsoft.com
The CS101 explanation of a Vector that copies values around whenever it exceeds its capacity is incorrect in many cases.
When I worked on perf at Windows, I vaguely recall someone telling me that the Windows impl doesn't do that for some reason. I'm curious if Raymond will cover why.
I mean, I guess you can put them near the end of pages already occupied by other things, though then you need more knowledge/control of other memory allocations in the program...
In practice it is very common for C++ developers to preallocate a region of memory upfront that is large enough to handle their dataset without having to go to such an extreme and non-portable length.
None of this contradicts the CS101 explanation, preallocating memory is entirely consistent with the fundamental understanding of how dynamic arrays work.
Now getting commit from reserve might fail, as you've mentioned because Windows does not overcommit, but it's possible to a degree.
I guess same with really large vector can be done.
Then the time it takes to move the vector to a new location is amortized as the vector grows. Then push() takes constant time.
So the CS101 is optimal for the study of computer science.
Someone did a nice trick long time ago the other way around using std::basic_string with say... float or custom structure - for the benefit of "small vector optimization"