c++ - Why below exception safety code using auto_ptr is different? -
here's code not exception safe
//header file declaration void f(auto_ptr<t1>, auto_ptr<t2>); //implementation file: f(auto_ptr<t1>(new t1), auto_ptr<t2>(new t2));
exception safe solution above suggested :
//implementation file: { auto_ptr<t1> t1(new t1); auto_ptr<t2> t2(new t2); f(t1, t2); }
my question why it's different when both uses auto_ptr handle resource allocation?
this problem-solution part of "more exceptional c++" herb sutter.
the problem first code snippet order 2 sub-expressions building f() parameters executed undefined c++ standard. is, if happens like:
- allocate & construct t1
- auto_ptr takes ownership of t1
- allocate & construct t2
- auto_ptr takes ownership of t2
this work fine. quite possible order like:
- allocate & construct t1
- allocate & construct t2
- auto_ptr takes ownership of t1
- auto_ptr takes ownership of t2
and in case if step 2 (alloc t2) throws, allocated memory t1 leak irretrievably.
for prevent this, explicit ordering done in second code snippet you've provided.
Comments
Post a Comment