I believe the accepted answer is incorrect.
If the content of the vector
is POD type (e.g., int
as in the question, orchar
etc.), then reserve()
ed memory is well-behaved objects, and the standard ensures nothing unexpected should be done to storage between size()
and capacity()
.
My argument, with quotation and reference to the Standard, was given in my answer https://stackoverflow.com/a/69141237/2791230. Here, I show in particular why the concerns in the accepted answer cannot happen.
“Perhaps [reserve()
ed memory] can be used for some internal data.” No, it can not be. Consider insert()
elements to the end of the vector, until reserve()
ed memory is filled up. The Standard ensures there are no side effects other than the apparent filling (and its results, e.g., changing size()
). Thus, it would be contrary to the Standard if some internal data are overwritten by insert()
(which is of course a side effect).
“Perhaps the address space is just reserved and not mapped to actual RAM?” This is more obviously impossible, because there are already objects living in the reserve()
ed memory, see the referred answer for detail.
In general, I think people are too ready to claim something is UB. Unless reference is given that the Standard explicitly says something is UB, all claims that “it is UB” should mean “I do not know it is defined, so I think it is UB,” because UB means “it is nowhere defined in the whole Standard.”