idioms - C++ Is using auto_ptr references as out variables idiomatic? -



idioms - C++ Is using auto_ptr references as out variables idiomatic? -

suppose want write mill method supposed allocate heterogeneous objects on heap , homecoming them caller. thinking of designing api this:

bool makeem(auto_ptr<foo>& outfoo, auto_ptr<bar>& outbar) { ... if (...) { homecoming false; } outfoo.reset(new foo(...)); outbar.reset(new bar(...)); homecoming true; }

this allows caller this:

auto_ptr<foo> foo; auto_ptr<bar> bar; makeem(foo, bar);

my question is: "is idiomatic? if not, right way this?"

the alternative approaches can think of include returning struct of auto_ptrs, or writing mill api take raw pointer references. both require writing more code, , latter has other gotchyas when comes exception safety.

you don't have create own struct homecoming 2 values - can utilize std::pair. in case there isn't much syntactic overhead in returning 2 values. solution have problem ".first" , ".second" aren't descriptive names, if types involved , name of function create intent clear plenty that's not problem.

if using c++0x utilize unique_ptr insted of auto_ptr , caller can utilize auto instead of having type longer std::pair<std::unique_ptr<a>, std::unique_ptr<b>>. if not using c++0x might consider using typedef instead.

if homecoming 2 values won't have space bool. utilize c++0x tuple homecoming 3 values. indicate error throwing exception or returning null pointers. prefer exception assuming error rare/exceptional.

as other answers have pointed out, preferable have 2 separate functions each homecoming single object. if can't because initialization of 2 objects inextricably linked create class encapsulates initialization. pass necessary info create 2 objects constructor (requires exception signal errors) , have 2 methods on class yield 1 object each.

c++ idioms auto-ptr

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -