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? 回答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