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

后端 未结 2 544
再見小時候
再見小時候 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:08

    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.

提交回复
热议问题