There is no realloc
in C++; Of course you can always allocate a new block with new
, copy the old block to the new block, free the old block with delete
.
The problem is that realloc can often be faster than this - this happens when the memory block is re-sized 'in place' - that is the return value of realloc
happens to be the same as the argument pointer value; this also avoids the copying of memory from old block to new block.
What does the standard say - is one allowed to pass pointer returned by the global new
operator to realloc
? (in glibc both new
and malloc
are using the same allocator, so there should not be a practical problem here). Does the C++ standard have anything to say on this subject?
(the current glibc standard C++ library does not do realloc, even in vector - because once an object has been allocated the runtime can't call the destructor in place on the old memory block and call placement new on the new block - if the memory block has been moved by realloc
that is. It would have been simpler if the standard library would have had an in-place realloc
that can't move the argument block to a new location)
edit:
Actually some memory allocators have an in-place realloc
function; these are of course non-standard.
- jemalloc has an API called
rallocm
with flagALLOCM_NO_MOVE
- dlmalloc (Doug Lea malloc) has an API called
dlrealloc_in_place
If you use jemalloc or dlmalloc for global operator new
and delete
, then you could use these non standard functions for a vector class that attempts in-place realloc
before it does a moving malloc
with copying. Or one could petition the C++ standard committee to add a global non-moving reallocation method to the standard.
edit:
or you can do a vector class where memory management is done via malloc
/realloc
/free
, but this implementation may only be instantiated if the element type is plain old data (i.e. if std::is_pod
returns true on the type that the vector is holding).