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

后端 未结 2 541
再見小時候
再見小時候 2021-01-07 11:46

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

2条回答
  •  失恋的感觉
    2021-01-07 12:25

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

提交回复
热议问题