From Bjarne Stroustrup's FAQ:
If you feel the need for realloc() - and many do - then consider using a standard library vector.
I'll preface my question by agreeing that std::vector
is better for many reasons, and I personally would always choose to use it over writing my own dynamic arrays with C memory allocation.
But, std::vector
fragments memory as it grows because C++ has no equivalent of realloc
(edit To clarify, I know that std::vector
's storage is contiguous and won't get fragmented, I mean fragmentation of the memory space caused by allocating and deallocating, which realloc
can avoid by extending an existing allocation). So is it fair to always recommend it over realloc
? With great care, couldn't you write something that works just like std::vector
but using C allocation functions, which has the possibility to grow its memory without moving its address and copying existing elements, making it as good or better in terms of fragmentation and performance?
And relatedly (bonus question!), why doesn't C++ have an equivalent to realloc
? It seems like an odd thing to omit in a language that is so focused on performance. The section in Bjarne's FAQ has exactly that title (minus emphasis), but the answer doesn't address the 'why'. Was it just an accidental omission? Is there some fundamental incompatibility with how new
/delete
work? Does it not really give the benefits it seems to in practice?
Edit: ok, so I had neglected to consider the C nastiness of realloc
- std::vector
can't be rewritten using realloc
because it only works with PODs, doesn't throw and so on. Perhaps a POD-only container written to deal with the nastiness would be a good idea for some situations. In any case though, the more interesting question becomes: would std::vector
benefit from a C++ equivalent of realloc
, which has (more or less) been answered here:
Does std::vector *have* to move objects when growing capacity? Or, can allocators "reallocate"?
Sadly, the answer seems to be "yes, but the standards committee didn't vote it in". Here's hoping.
realloc
has the ability to expand an existing block though, which is surely as good or better than that? – Cockestd::vector
but might be better. – Cockestd::vector
" - apart from only working for trivial types, and not giving you any control over the allocation strategy. – Workbench