Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Detect Stack Unwinding in a Destructor

I have a simple C++ object that I create at the start of function F() to ensure two matched functions (OpDo, OpUndo) are called at the start and return of the F(), by using the object's constructor and destructor. However, I don't want the operation to be undone in case an exception was thrown within the body of F(). Is this possible to do cleanly? I have read about std::uncaught-exception, but its use does not seem to be recommended.

like image 561
ihamer Avatar asked Oct 25 '10 20:10

ihamer


People also ask

What is stack unwinding explain with an example?

When an exception is thrown and control passes from a try block to a handler, the C++ run time calls destructors for all automatic objects constructed since the beginning of the try block. This process is called stack unwinding. The automatic objects are destroyed in reverse order of their construction.

Which convention is used to stack unwind in caller?

JSC's Calling Convention This convention is used by the interpreter, the baseline JIT and its optimizing compilers DFG and FTL, such that JS-functions emitted by different compilers are able to interoperate with each other. All arguments are passed on the stack, there are also some additional values passed as argument.

What is stack unwind?

Stack Unwinding in C++ The stack unwinding is a process where the function call stack entries are removed at runtime. To remove stack elements, we can use exceptions. If an exception is thrown from the inner function, then all of the entries of the stack is removed, and return to the main invoker function.

Can we have try catch in destructor?

You must avoid having a destructor that may throw an exception, it's OK to catch and manage them properly. You might care to read N4152, "uncaught exceptions", voted into C++17.


1 Answers

Most people have used std::uncaught_exception() to try to tell if an exception is pending, so they can throw an exception from a destructor if there isn't one already. That is generally considered Not A Good Idea.

If you want to not undo an operation if an exception has thrown, it should do the trick.

Remember that the destructor is your last chance to release any resources an object has, because after the destructor ends the object does not exist, and any resources it held are now permanently leaked. If OpDo() allocates any memory or file handles or whatever, you do need to deal with that in the destructor no matter what.

like image 147
David Thornley Avatar answered Oct 21 '22 12:10

David Thornley