仅释放分配了"operator new"的一部分内存

Aun*_*vre 2 c++ memory memory-leaks memory-management

从理论上讲,如果使用内存中的空间分配operator new,是否可以以零散的方式释放内存?例如,如果void *mem = operator new(sizeof(int)*2)用于为两个int*变量分配一个内存地址,一个在mem另一个中mem+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
Run Code Online (Sandbox Code Playgroud)

Mar*_*k B 6

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

要求:ptr应为空指针或其值应为先前调用(可能已替换)operator new(std::size_t)返回的值,或者operator new(std::size_t,const std::nothrow_t&)尚未通过中间调用无效的值operator delete(void*).

对于破坏分配的内存而言,我认为你不能比这更明确:标准不允许这样做.