如何从std :: list正确删除指针? [英] How to properly delete pointer from a std::list?
问题描述
我通过 new
创建一个对象,然后稍后在对象设置后将指针添加到std :: list。
I'm creating an object via new
, then later adding the pointer to an std::list once the object is set up.
删除指针并从列表中擦除数据而不会导致内存泄漏的正确方法是什么?
What is the correct way of deleting a pointer and erasing the data from the list without causing memory leaks?
推荐答案
而不是手动循环来搜索元素,我宁愿使用 std :: find_if
Instead of manual loop to search the element, I would rather use std::find_if
auto it = std::find_if(lst.begin(),
lst.end(),
[&val](datalist const &d) { return d.index == val; });
if ( it != lst.end() )
{
delete *it;
lst.erase(it);
}
这不是说你做错了。
但是,如果你考虑使用某种形式的智能点,你的代码将会改善,例如 std :: unique_ptr
, std :: shared_ptr
或boost的智能指针,那么你不必自己管理内存。
However, your code will improve if you consider using some form of smart points, such as std::unique_ptr
, std::shared_ptr
, or boost's smart pointers, then you don't have to manage memory yourself.
这篇关于如何从std :: list正确删除指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!