Is it safe to push_back 'dynamically allocated object' to vector?
问题 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