I wrote a lot of software modules around the general theme of a long-lived vector, which should update the content several times (at an undefined frequency).
Idiomatic implementation:
void LongLived::reconfigure(const InputT& whatever_input) { m_vector.clear(); m_vector.reserve(whatever_input.size()); populate(m_vector, whatever_input); }
Note that an idiomatic implementation will never reduce the capacity of the internal buffer. What if it’s not normal? Just use shrink_to_fit() , I thought:
void LongLived::reconfigure(const InputT& whatever_input) { m_vector.clear(); m_vector.reserve(whatever_input.size()); m_vector.shrink_to_fit(whatever_input.size());
Oh, how good it would be ... But, to my surprise, it does not compile because shrink_to_fit() does not accept a number!
It is assumed that the shrink_to_fit() path shrink_to_fit() to be that you are filling the vector first. Then you call shrink_to_fit() , which will get the capacity requirement from the number of elements in the vector after the fact, but this is clearly suboptimal if I could say it in advance, because now all this content should be moving.
Purpose: I would like to use the vector_reserve_or_shrink() function in this context:
void LongLived::reconfigure(const InputT& whatever_input) { m_vector.clear(); vector_reserve_or_shrink(m_vector, whatever_input.size());
I'm actually not obsessed with shaving every unused byte from a vector. Rather, I would be happy to leave it to some implementation defined as shrink_to_fit() , which might know something about the quirks of the dispenser and might do nothing. Thus, you do not run the risk of making an abstraction inversion that negates any lower levels of optimization. For example, let's say that the granularity of the allocator is 16: then a vectorial implementation can give you 15 bytes for free when you ask one, as far as I know, that it would be simply counterproductive to try to return.