[英]Transfer Dynamic Array to new Dynamic Array, Delete Dynamic array filled with Dynamic Objects
如果我創建一個動態斑馬數組,然后說,我創建一個新的臨時數組,我想在其中傳輸原始數組中的對象。
然后我將指針從原始數組移動到臨時。 在 move array = temp 之前我需要刪除舊的數組項嗎?
此外,我似乎泄漏但不知道為什么,我似乎刪除了 arrays 和指針。
class Zebra {
public:
//int age = 0;
};
int main() {
Zebra** array = new Zebra * [10];
for (int i = 0; i < 10; i++) {
array[i] = new Zebra;
}
Zebra** temp = new Zebra * [20];
for (int i = 0; i < 10; i++) {
temp[i] = array[i];
}
// do i need to delete the old array items before move array = temp?
array = temp;
delete[]temp;
temp=NULL;
for (int i = 0; i < 10; i++) {
delete[]array[i];
array[i]=NULL;
}
delete[]array;
array= NULL;
}
你有你要向后刪除的東西,你想要:
delete[] array;
array = nullptr;
array = temp;
for (int i = 0; i < 10; i++) {
delete array[i];
array[i] = NULL;
}
delete[] array;
array = NULL;
請注意,您還對delete[]
的使用不匹配,其中delete
應該單獨用於釋放array[i]
元素。
為什么會這樣?
最初,您為指針array
分配創建一個 memory 塊,其中包含十個指向Zebra
的指針。 然后,當您創建兩倍於array
的temp
並將array
中的每個指針分配給temp
時,您的temp
將保存每個array[i]
的起始地址(其中0 <= i < 10
)。
您所做的只是delete[] array
,它釋放了 memory 的塊,該塊保存了指向Zebra
的10
指針的原始存儲。 當你分配array = temp;
現在數組指向 memory 的新塊,其中包含20
指向Zebra
的指針。
因此,在您的重新分配方案中,您剛剛創建了一個更大的指針塊,將所有從array
分配給temp
,刪除了原始指針塊,並將新的指針塊分配給array
(完成)。 (基本上做realloc()
在 C 中所做的)
完整的例子是:
#include <iostream>
class Zebra {
public:
//int age = 0;
};
int main() {
Zebra **array = new Zebra*[10];
for (int i = 0; i < 10; i++) {
array[i] = new Zebra;
}
Zebra **temp = new Zebra*[20];
for (int i = 0; i < 10; i++) {
temp[i] = array[i];
}
delete[] array;
array = nullptr;
array = temp;
for (int i = 0; i < 10; i++) {
delete array[i];
array[i] = nullptr;
}
delete[] array;
array = nullptr;
}
Memory 使用/錯誤檢查
valgrind ./bin/zebra
==22402== Memcheck, a memory error detector
==22402== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==22402== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==22402== Command: ./bin/zebra
==22402==
==22402==
==22402== HEAP SUMMARY:
==22402== in use at exit: 0 bytes in 0 blocks
==22402== total heap usage: 13 allocs, 13 frees, 72,954 bytes allocated
==22402==
==22402== All heap blocks were freed -- no leaks are possible
==22402==
==22402== For counts of detected and suppressed errors, rerun with: -v
==22402== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.