- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
是否可以保证 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 byptr
and returns a pointer to a new object that has the size specified bysize
. 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, therealloc
function behaves like themalloc
function for the specified size. Otherwise, ifptr
does not match a pointer earlier returned by thecalloc
,malloc
, orrealloc
function, or if the space has been deallocated by a call to thefree
orrealloc
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/
我有一个具有可变数量子元素的固定大小的 div。我不知道 children 的大小。目标是缩小它们以适合父级。 例子: .parent { width: 100px; height: 100p
我是一名优秀的程序员,十分优秀!