gpt4 book ai didi

c++ - 仅释放分配给 "operator new"的一部分内存

转载 作者:搜寻专家 更新时间:2023-10-31 00:12:54 26 4
gpt4 key购买 nike

理论上,如果内存中的空间是使用 operator new 分配的,是否有可能以零散的方式释放该内存?例如,如果使用 void *mem = operator new(sizeof(int)*2) 将内存地址分配给两个 int* 变量,其中一个位于 memmem+sizeof(int) 中的另一个,是否可以释放其中一个的内存,而不释放另一个?

我的理解是operator new只是分配内存,并没有调用任何构造函数,所以placement new是用来在内存中的精确空间调用构造函数.如果这些分配的内存地址是已知的,但在内存中不一定是线性的(例如,存储在内存池类的链表中),我想会有一种适当的方法来释放分配的内存遍历内存地址链表并释放分配大小的内存。但是,通过将内存分配给指向适当大小的数据类型的指针,总是会引发运行时错误。

是否有合适的方法来做到这一点?

理论例子:

// This works fine
uintptr_t mem1 = reinterpret_cast<uintptr_t>(operator new(sizeof(int)));
int *a = new(reinterpret_cast<void*>(mem1)) int(1);
printf("a|*a\t\t%p|%d\n", a, *a);
delete a;

// Both of the pointers can be assigned to the appropriate positions...
uintptr_t mem2 = reinterpret_cast<uintptr_t>(operator new(sizeof(int) * 2));
int *b = new(reinterpret_cast<void*>(mem2)) int(2);
printf("b|*b\t\t%p|%d\n", b, *b);
int *c = new(reinterpret_cast<void*>(mem2+sizeof(int))) int(3);
printf("c|*c\t\t%p|%d\n", c, *c);

// ...but attempting to delete them results in a runtime error.
operator delete(b);
operator delete(c);
//using "operator delete(reinterpret_cast<void*>(mem2));" works just fine, but I'm operating on the assumption that the addresses may be non-linear, in a linked-list of addresses of a constant size

最佳答案

18.6.1.1/12(void operator delete(void* ptr) noexcept):

Requires: ptr shall be a null pointer or its value shall be a value returned by an earlier call to the (possibly replaced) operator new(std::size_t) or operator new(std::size_t,const std::nothrow_t&) which has not been invalidated by an intervening call to operator delete(void*).

我认为在销毁分配的内存方面没有比这更明确的了:标准不允许这样做。

关于c++ - 仅释放分配给 "operator new"的一部分内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28884791/

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