gpt4 book ai didi

c++ - 当缓冲区缩小时,是否保证 realloc 就位?

转载 作者:可可西里 更新时间:2023-11-01 15:39:55 25 4
gpt4 key购买 nike

是否可以保证 realloc() 总是就地缩小缓冲区?因此:

new_ptr = (data_type *) realloc(old_ptr, new_size * sizeof(data_type));

如果 new_size < old_size(当然 new_size == 0 时除外),将始终给出 new_ptr == old_ptr。它以这种方式工作(对我来说)似乎是明智的,但很好奇标准是否强制执行它。

我正在研究非 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
}

我希望即使数据类型具有自引用/指针或其他任何东西,就地“收缩”也会很健壮......

最佳答案

没有。

就是这样。这些都不是“它可能在某些体系结构中工作”或“它应该根据经验”。该标准明确指出地址可能会更改,所以只依赖那个,仅此而已。无论如何,您询问是否保证 - 答案是肯定的(a)

就标准编码而言:做或不做。没有“尝试”:-)


来自 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.


(a) 如果您想知道为什么您不会将一个缓冲区分成两个较小的缓冲区(保留一个并将另一个返回到空闲列表) 为了提高效率,我至少想到了一种可能性。

如果您有不同的池用于不同大小的分配(例如,可能使用不同的分配策略),将数据移至池中以进行较小的分配可能是有意义的。您从单独的池中获得的效率 yield 可能超过保留内存的 yield 。

但这只是一个例子,我不知道是否有任何实现可以做到这一点。如前所述,您应该依赖于标准要求,即内存即使在缩小时也可能移动。

关于c++ - 当缓冲区缩小时,是否保证 realloc 就位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3162502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com