c++ RAII destructor exception -


as far understand raii refers acquire resources in ctor , release them in dtor.

ctor acquires resources , can fail, resulting in exception. dtor releases resources , can fail, exception dtors foobar no exception.

class {   a() throw(ex) { // acquire resources }   ~a() throw() { // release resources } } 

so if user of class should made aware of error happening in a´s uninitialisation can outsource uninitialisation function throws, called dtor swallows exceptions:

class {   a() throw(ex) { // acquire resources }   ~a() throw() { try {release(); } catch(...) {} }    void release() throw(ex) { // release resources } } 

that way user can call exit() if wants feedback release-error or ignore letting dtor it´s job when goes out of scope (e.g. other exception occurs used).

to prevent multiple executions of exit() (first explicitly user, later indirect dtor) have add init-status:

class {   bool init;   a() throw(ex) { init = true; // acquire resources }   ~a() throw() { try {release(); } catch(...) {} }    void release() throw(ex) {     if(!init) return;     init = false;     // release resources    } } 

are there better ways or have implement pattern every time resource-release can fail , want know it?

releasing resources shouldn't have scope fail. example, releasing memory can implemented in form doesn't throw exception. raii intended clean-up resources , not deal error resulting substantial clean-up.

clearly, there clean-up operations fail. example, closing file fail, e.g., because closing flush internal buffer , may fail because disc file writing full. if clean-up operation fails, there should suitable release operation , if users interested in reporting errors clean-up, should use method: in normal path, there opportunity handle error.

when release made part of handling existing error, i.e., exception thrown , release operation isn't reached, exceptions need eaten destructor. there may handling method to, e.g., log message of exception thrown exception shouldn't escape destructor.


Comments

Popular posts from this blog

android - Automated my builds -

how to proxy from https to http with lighttpd -

python - Flask migration error -