Not exactly; for_each
requires a function or object that can be invoked with ()
, and delete
is neither a function nor an object. You will have to wrap it up in a function (or function object), perhaps like:
struct Deleter
{
void operator()(Obj* obj) {delete obj;}
};
std::for_each(objs.begin(), objs.end(), Deleter());
But you should be very careful managing object lifetimes with raw pointers, especially if you're passing them around. You'll need to remember to delete them if you erase them from the vector
, or reassign them, or if you clear the vector
, or if an exception, break or function return might cause the vector to be destroyed. In general, it's always better to separate the responsibilities of resource management and resource usage.
You'd be better off with a vector of objects, unless Obj
is a polymorphic base class, or the objects really are big or complicated enough that copying them will have a noticeable impact on performance. If that is the case (and you've profiled it to be sure that it's the case), you should consider a vector of smart pointers (shared_ptr
, or unique_ptr
if your compiler supports it), or Boost's ptr_vector
.
Getting in the habit of using automatic resource management classes will save you a lot of headaches in the future.