Suppose I have a std::vector<Obj *> objs (for performance reasons I have pointers not actual Objs).
I populate it with obj.push_back(new Obj(...)); repeatedly.
After I am done, I have to delete the pushed-back elements. One way is to do this:
for (std::vector<Obj *>::iterator it = objs.begin(); it != objs.end(); ++it) {
delete *it;
}
However, I am interested if I can use for_each algorithm to do the same:
#include <algorithm>
...
for_each(objs.begin(), objs.end(), delete);
What do you think?
Your problem is that
deleteis not a function, but rather a keyword and as such you can’t take it’s address.In C++0x, there will be a
std::default_deleteclass (used bystd::unique_ptr), which you could use, or – as everyone’s saying – writing one yourself would be trivial (the standard one also raises a compile error, if you try to delete an incomplete type).