这段代码是否会导致内存泄漏:
int main(){
int * a = new int[10];
int * b = new int[10];
for(int i = 0 ; i < 10; i++)
{
a[i] = 1;
b[i] = 1;
}
for(int i = 0 ; i < 10; i++)
{
a[i] = b[i]; //each a[i] is allocated 4 bytes on heap
//when we copy b[i] into a[i] do we loose
//the reference to a[i] (hence a leak),
//and replace that reference
//with a reference to a new value?
}
delete[] a;
delete[] b;
}
最佳答案
不,那里没有泄漏。您只是在复制数组中的值。将阵列想象成更衣室中的两排储物柜——您只需复制一个储物柜中的内容,然后将其放入另一排储物柜中;储物柜本身留在原处。
关于c++ - 将一个数组的内容复制到另一个数组会导致内存泄漏吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1579663/