我正在尝试在内存中一个一个地分配一阶指针。二阶指针必须遍历此队列并处理在该指针上创建的对象。当我分配对象队列(而不是指向它们的指针)时,放置 new 工作正常,但是当我尝试使用指针进行相同操作时,麻烦就会发生。
int* p;
p = new int(1);
printf("%p - %d\n", p, *p); // address of int and its value
delete p;
创建和删除第一个对象以使用某个地址初始化指针,下一个对象将循环创建
p = new(p) int(2); // (p) - memory will be allocated at address
// on which p points
printf("%p - %d\n", p, *p); // address of int and its value
delete p;
p++;
p = new(p) int(3); // (p) - memory will be allocated at address
// on which p points
printf("%p - %d\n", p, *p); // address of int and its value
delete p;
输出:
01C1FFD0 - 1
01C1FFD0 - 2
01C1FFD4 - 3;
int** pp;
pp = new int*;
printf("%p\n", pp); // address of int*
*pp = new int(1);
printf("%p - %d\n", *pp, **pp); // address of int and its value
delete *pp;
delete pp;
pp = new(pp) int*;
printf("%p\n", pp); // address of int*
*pp = new int(2);
printf("%p - %d\n", *pp, **pp); // address of int and its value
delete *pp;
delete pp;
pp++;
pp = new(pp) int*;
printf("%p\n", pp); // address of int*
*pp = new int(3);
printf("%p - %d\n", *pp, **pp); // address of int and its value
delete *pp;
delete pp;
如果 int 不是由 *pp 创建的,那么如果 pp 递增,那么以后删除 pp 是不真实的,如果 int 是由 *pp 创建的,那么地址和第二个值就会有些奇怪。
输出:
01C1FFD0
01C1FFE0 - 1
01C1FFD0
01C1FFD0 - 29491152
01C1FFD4
01C1FFD0 - 3
对于如何正确组织此队列的建议,我将不胜感激。