How to properly delete pointer from a std::list?

怎甘沉沦 提交于 2019-11-30 20:20:38

问题


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?


回答1:


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);
}

That is not to say that you're doing it incorrectly.

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.




回答2:


If you change your std::list to hold datalist instances instead of datalist* pointers, then you don't have to delete the datalist instances manually anymore. When you remove an element from a std::list (or any other STL container, for that matter), the element's data is freed automatically for you. If the element is a class/struct with a destructor defined, the destructor will be called.

Try this:

std::list<datalist> m_DataList;

.

datalist AR; // <-- local variable on the stack, freed when out of scope
AR.index = ...;
AR.number = ...;
mylist.push_back(AR); // <-- pushes a copy-constructed instance of the variable

.

std::list<datalist>::iterator Iter1 = m_DataList.begin();
while(Iter1 != m_DataList.end()) 
{ 
    if (Iter1->index == m_SomeVar)     
    { 
        m_DataList.erase(Iter1); // <-- copied datalist instance is freed automatically
        break; 
    } 

    ++Iter1; 
} 


来源:https://stackoverflow.com/questions/10854274/how-to-properly-delete-pointer-from-a-stdlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!