【问题标题】:Deleting list with pointers and also the object must be cleared删除带有指针的列表以及必须清除对象
【发布时间】:2016-03-18 20:06:04
【问题描述】:

下面是用于说明我的问题的相同 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。 (另外,不要使用类型名作为变量名。)

标签: c++ list object erase


【解决方案1】:

list.erase 排除在for 循环之外并在完成后调用list.clear 会更简单。

如果要保留 for 循环,则需要对其进行修复。它应该是这样的:

for (auto iter = list.begin(); iter != list.end();) {
    delete *iter;
    iter = list.erase(iter);
}

erase 将迭代器返回到被擦除元素之后的元素,因此您无需在循环中递增。此外,您的原始循环将减少 iter 以指向未定义行为 (UB) 的列表开头之前。

【讨论】:

  • 您好,我再次更新了代码,请您检查一下,如果仍然有问题,请告诉我。如果我没记错的话,仅仅删除指针不会清除对象。所以我要删除对象并清除它。
  • @lok​​eshkondi 擦除时您没有正确处理迭代器;再次检查我的代码。由于您要摆脱所有内容,因此最好不要在循环中擦除并在循环完成时调用clear
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
  • 2017-01-26
  • 2020-09-10
  • 2012-11-20
  • 1970-01-01
  • 2011-05-02
  • 2012-09-10
相关资源
最近更新 更多