c++ - Is it safe to push_back 'dynamically allocated object' to vector? -


whenever need add dynamically allocated object vector i've been doing following way:

class foo { ... };  vector<foo*> v;  v.push_back(new foo);  // stuff foo in v  // delete foo in v 

it worked , many others seem same thing.

today, learned vector::push_back can throw exception. means code above not exception safe. :-( came solution:

class foo { ... };  vector<foo*> v; auto_ptr<foo> p(new foo);  v.push_back(p.get()); p.release();  // stuff foo in v  // delete foo in v 

but problem new way verbose, tedious, , see nobody's doing it. (at least not around me...)

should go new way?
or, can stick old way?
or, there better way of doing it?

if care exception-safety of operation:

v.reserve(v.size()+1);  // reserve can throw, doesn't matter v.push_back(new foo);   // new can throw, doesn't matter either. 

the issue of vector having responsibility freeing objects pointed contents separate thing, i'm sure you'll plenty of advice ;-)

edit: hmm, going quote standard, can't find necessary guarantee. i'm looking push_back not throw unless either (a) has reallocate (which know won't because of capacity), or (b) constructor of t throws (which know won't since t pointer type). sounds reasonable, reasonable != guaranteed.

so, unless there's beneficial answer on over question:

is std::vector::push_back permitted throw reason other failed reallocation or construction?

this code depends on implementation not doing "imaginative". failing that, solution question can templated up:

template <typename t, typename container> void push_back_new(container &c) {     auto_ptr<t> p(new t);     c.push_back(p.get());     p.release(); } 

usage isn't tedious:

struct bar : foo { };  vector<foo*> v; push_back_new<foo>(v); push_back_new<bar>(v); 

if it's factory function rather new modify template accordingly. passing lot of different parameter lists in different situations difficult, though.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -