The problem with realloc
is that is may move the existing data to a different range of contiguous addresses. Should it need to do so, given it's a C function the data is copied without any nod to C++ object lifetime:
- copy/move constructors aren't used
- destructors aren't invoked afterwards for the source objects
This can cause fatal consequences - for example, when the objects being moved contain pointers/references that remain pointing at addresses in the memory area being vacated.
Sadly, normal malloc
implementations don't allow a callback hook allowing you to replace the memory-content-copying code with your own C++-safe implementation. If you're determined you could try to find a more flexible "malloc" library, but it's unlikely to be worth the hassle and risk.
Consequently, in the general case you should use new
to change your capacity, copy/move each object, and delete
the originals afterwards.
If you're certain your data is simple enough that a memcpy
-style relocation won't cause adverse consequences, then you can use realloc
(at your own risk).