下面是用於說明我的問題的相同的C++代碼
我知道其他工作方法,但有興趣知道下面的代碼是否錯誤?用指針刪除列表也是必須清除的對象
Void pupulatelist()
{
//populating the list with some int pointers,in actual i have some other objects to delete when accessed each time.
for(int i =0;i<5;i++)
{
int *p = new int(i);
list.push_back(p);
}
//want to delete and erase the contents of the above list
// if i dont use erase my actual code is crashing.
for(std::list<int *>::iterator iter = list.begin(); iter != list.end(); ++iter)
{
delete(*iter);
list.erase(iter--);
}
}
取消'list.erase'並在循環之後調用'list.clear'。 (另外,請不要使用類型名稱作爲變量名稱。) – molbdnilo