theTime3
theTime3

Reputation: 19

How to properly delete pointer from a 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?

Upvotes: 1

Views: 471

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595711

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

Upvotes: 3

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361312

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.

Upvotes: 4

Related Questions