Are there any guarantees that realloc() will always shrink a buffer in-place?? So that the following:
new_ptr = (data_type *) realloc(old_ptr, new_size * sizeof(data_type));
will always give new_ptr == old_ptr if new_size < old_size (except of course when new_size == 0). It seems sensible (to me) that it would work this way, but was curious whether the standard enforced it.
I'm looking at the reallocation of arrays of non-POD data types, and if the above behaviour was guaranteed was thinking that the following strategy might at least allow efficient "shrinking":
if (new_size > old_size)
{
// malloc() a new buffer
// use placement copy constructor to copy old objects over
// free() old buffer
}
else
if (new_size < old_size)
{
// explicit destruction of unneeded objects
// realloc() buffer
}
I"m expecting that an in-place "shrink" would be robust even if the data type had self references/pointers or whatever...