Suppose I have a std::vector
(for performance reasons I have pointers not actual Obj
s).
I populate it with obj.push
While you can do this (GMan has shown a solution), having containers with naked pointers to owned resources is a strong code smell. For example, in this code:
void foo()
{
std::vector bar;
fill(bar);
use(bar);
std::for_each(objs.begin(), objs.end(), delete_ptr()); // as GMan suggests
}
if use()
throws, you'll leak objects.
So it's better to use smart pointers for this:
std::vector< std::shared_ptr > bar;