Whenever I need to add dynamically allocated object into a vector I've been doing that the following way:
class Foo { ... };
vector<Foo*> v;
v.push_back(new Foo);
// do stuff with Foo in v
// delete all Foo in v
It just worked and many others seem to do the same thing.
Today, I learned vector::push_back can throw an exception. That means the code above is not exception safe. :-( So I came up with a solution:
class Foo { ... };
vector<Foo*> v;
auto_ptr<Foo> p(new Foo);
v.push_back(p.get());
p.release();
// do stuff with Foo in v
// delete all Foo in v
But the problem is that the new way is verbose, tedious, and I see nobody's doing it. (At least not around me...)
Should I go with the new way?
Or, can I just stick with the old way?
Or, is there a better way of doing it?