c++ - Will the destructor of an object be called if a function returns early or throws an exception? -


in following code, use wrapper object temporarily store stuff db in memory. question simple:

can sure destructor called? particularly worried cases a) testcondition true , function returns inner scope of scope in tempobj constructed b) runtime error occurs during execution of function (which caught @ higher level)

(as side question: way temporarily store data? in application, somefunc() save/export function of current db.)

class tempstore { public:     tempstore() {/* delete stuff db , store in memory*/}     ~tempstore() {/* write stuff db*/} };  void somefunc(bool testcondition) {     tempstore tempobj = tempstore();     // code     if (testcondition)         return; //early return     // more code } 

the destructor of automatic object called when program leaves object's scope. includes returning function (early or otherwise), , leaving via exception - long exception handled. in case of exception, it's called during stack unwinding before exception handled.

it might not called in cases, including:

  • leaving via call longjmp; gives undefined behaviour;
  • leaving via exception that's not handled; it's unspecified whether stack unwound.
  • terminating program (e.g. calling exit, or raising signal causes termination).

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -