[問題] 需要特別在 catch 中去 delete 變數嗎?
如題,假設我 new 了一個變數並在結束時delete。
而我的 function 中有使用 try + catch。
那麼,假設真的發生了exception,會跑到catch。
我需要為了避免 memory leakage 而在 catch 中手動加入 delete 的 code 嗎?
意即需要特地加入下面 code 中的紅色部分嗎?
感謝。
int data = new int [1024];
try
{
// do many things
}
catch (...)
{
if (data)
{
delete [] data;
data = NULL;
}
}
// 原本就有在結束時 delete
if (data)
{
delete [] data;
data = NULL;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.66.17.92
※ 編輯: Fightsea 來自: 61.66.17.92 (12/30 11:07)
※ 編輯: Fightsea 來自: 61.66.17.92 (12/30 11:07)
→
12/30 11:10, , 1F
12/30 11:10, 1F
→
12/30 11:22, , 2F
12/30 11:22, 2F
→
12/30 11:23, , 3F
12/30 11:23, 3F
推
12/30 11:38, , 4F
12/30 11:38, 4F
→
12/30 11:38, , 5F
12/30 11:38, 5F
→
12/30 11:40, , 6F
12/30 11:40, 6F
→
12/30 11:40, , 7F
12/30 11:40, 7F
→
12/30 11:40, , 8F
12/30 11:40, 8F
→
12/30 11:41, , 9F
12/30 11:41, 9F
→
12/30 11:41, , 10F
12/30 11:41, 10F
→
12/30 11:41, , 11F
12/30 11:41, 11F
→
12/30 11:41, , 12F
12/30 11:41, 12F
→
12/30 11:43, , 13F
12/30 11:43, 13F
→
12/30 11:43, , 14F
12/30 11:43, 14F
→
12/30 11:44, , 15F
12/30 11:44, 15F
→
12/30 11:56, , 16F
12/30 11:56, 16F