从理论上讲,如果使用内存中的空间分配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 …Run Code Online (Sandbox Code Playgroud)