简体   繁体   English

重新分配后删除C ++中的数组指针是否安全?

[英]Is it safe to delete an array pointer in C++ after reassignment?

Suppose I'd like to swap two array pointers in C++ which I have allocated with new [] and different length. 假设我想交换两个用我分配的new []和不同长度的C ++数组指针。 Is it safe to delete [] them after swapping? 交换后delete []是否安全? What if they have the same length? 如果它们的长度相同怎么办?

int *a;
int *b;
int *tmp;

a = new int[5];
b = new int[10];
tmp = a;
a = b;
b = tmp;

delete [] a;
delete [] b;

Is it safe to delete [] them after swapping? 交换后删除[]是否安全?

Yes. 是。

What if they have the same length? 如果它们的长度相同怎么办?

The length is irrelevant. 长度无关紧要。

Yeah, you can. 是的,你可以。 The reason being is that the information needed to accurately free up that memory is managed by the free store (the heap in most cases). 原因是准确释放内存所需的信息由空闲存储(在大多数情况下为堆)管理。 So it knows how to delete based on address rather than variable. 因此,它知道如何根据地址而不是变量进行删除。 Often times this information is held in *(ptr - x) where x is the size of the tracking data. 通常,此信息保存在*(ptr - x) ,其中x是跟踪数据的大小。

Yes, you can surely delete the pointer once your swapping is done. 是的,交换完成后,您当然可以删除指针。 As you no longer need to point your array so in that case, it is safe to delete after swapping. 由于您不再需要指向数组,因此在这种情况下,可以安全地在交换后删除。

int *a;
int *b;
int *tmp;

a = new int[5];
b = new int[10];
tmp = a;
a = b;
b = tmp;

delete [] a;
delete [] b;

And this is the correct way of doing it. 这是正确的方法。 Great Job 很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM