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
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.