new_ptr = (data_type *) realloc(old_ptr,new_size * sizeof(data_type));
将会给new_ptr == old_ptr if new_size< old_size(当然当new_size == 0时).这对我来说似乎是合理的,但是好的是,这个标准是否执行了. 我正在考虑重新分配非POD数据类型的数组,并且如果上述行为得到保证,则认为以下策略可能至少允许有效的“收缩”:
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 }
我希望即使数据类型具有自己的引用/指针或任何内容,就地“收缩”将是强大的
解决方法
而已.没有一个这样的“它可能在一些架构中工作”或“应该根据经验”.该标准清楚地表明,地址可能会改变,所以依靠这一点,没有更多.
在编码到标准方面:做或不要.没有“尝试”:-)
从c99:
The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object shall be the same as that of the old object prior to deallocation,up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.
If ptr is a null pointer,the realloc function behaves like the malloc function for the specified size. Otherwise,if ptr does not match a pointer earlier returned by the calloc,malloc,or realloc function,or if the space has been deallocated by a call to the free or realloc function,the behavior is undefined. If memory for the new object cannot be allocated,the old object is not deallocated and its value is unchanged.
The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object),or a null pointer if the new object could not be allocated.