這是一個簡單的問題,我是一個初學者,但我只想確認這一點。如何替換一個動態數組而不會導致內存泄漏?
說我有一個類對象int * data,它指向一個5個整數的數組。假設我有一個函數可以用5個參數替換數據,如下所示。
void replaceData(int a, int b, int c, int d, int e){
int * temp = new int[5];
temp[0] = a;
temp[1] = b;
temp[2] = c;
temp[3] = d;
temp[4] = e;
data = temp;
}
我擔心這會導致內存泄漏,因爲如果數據已經有5個ints,他們仍然會在周圍浮動。爲了避免這種情況,我試圖改變它:
void replaceData(int a, int b, int c, int d, int e){
int * temp = new int[5];
temp[0] = a;
temp[1] = b;
temp[2] = c;
temp[3] = d;
temp[4] = e;
delete data; //would this prevent a memory leak?
data = temp;
temp = 0;
}
非常感謝您的意見!
謝謝!很有幫助。 – SemperCallide