c++ - How does stack unwinding work regarding destructor calls? -


let's suppose following simple example:

#include <iostream>  struct foo {     ~foo() {         std::cout << "~foo()" << std::endl;     } };  struct bar {     foo x;     bar() : x() {         throw -1;     }     ~bar() {         std::cout << "~bar()" << std::endl;     } };  struct baz {     ~baz() {         std::cout << "~baz()" << std::endl;     } };  int main() {     try {         baz y;         bar z;     } // destructor called constructed here?     catch(...) {     } } 

the output is

~foo() ~baz() 

so bar's destructor isn't called.

what mean kind of resource allocation intended released in bar's destructor?

e.g.

struct bar {     costlyresource cr;     bar() {         cr.open(); // aquire resource          // else throws ...         throw -1;     }     ~bar() {         if(cr.isopen()) {             cr.release(); // free resource         }     } }; 

for sake of exception safe implementation can ensure bar's resource member released?

for sake of exception safe implementation can ensure bar's resource member released?

you can catch, handle , rethrow anonymous excption in constructor:

struct bar {     costlyresource cr;     bar() {         try { // wrap whole constructor body try/catch             cr.open(); // aquire resource              // else throws ...             throw -1;          }          catch(...) { // catch anonymously              releaseresources(); // release resources              throw; // rethrow caught exception          }     }     ~bar() {         releaseresources(); // reuse code ro release resources     } private:     void releaseresources() {         if(cr.isopen()) {             cr.release(); // free resource         }     } }; 

see full example code here please.


as that's problem asked dynamic memory allocation done in constructors like

class myclass {      typea* typeaarray;      typeb* typebarray; public:      myclass() {          typeaaarray = new typea[50];          // else might throw here          typebaarray = new typeb[100];      }      ~myclass() {          delete[] typeaaarray;          delete[] typebaarray;      } }; 

the easiest way come on either use appropriate container (e.g. std::vector<typea>, std::vector<typeb>), or smart pointer (e.g. std::unique_ptr<typea[50]>).


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -