Will the object's destructor be called if the function returns earlier or throws an exception?
In the following code, I am using a wrapper object to temporarily store some stuff from a db in memory. My question is simple:
Can I be sure the destructor is called? I am especially worried about cases where a) is testCondition
true and the function returns earlier from the inner area of the scope tempObj
b) at the time of this function (which is caught at a higher level) some runtime error occurs
(As a side question: is this a good way to temporarily save some data? In my application, someFunc()
is the save / export function of the current db.)
class TempStore
{
public:
TempStore() {/* delete some stuff from a db and store this in memory*/}
~TempStore() {/* write this stuff back into the db*/}
};
void someFunc(bool testCondition)
{
TempStore tempObj = TempStore();
// some code
if (testCondition)
return; //early return
// some more code
}
source to share
The destructor of an automatic object is called when the program leaves the scope of the object. This includes returning from the function (earlier or otherwise) and exiting through the exception - as long as the exception is being handled. In case of an exception, it is called during packet unwinding before the exception is handled.
It may not be called in some cases, including:
- leaving on call
longjmp
; this gives undefined behavior; - leaving an exception that is not handled; it is undefined whether the stack will unwind.
- termination of a program (for example, calling
exit
or raising a signal that causes termination).
source to share
The destructor will be called if the program fails due to a seg failure or power outage or something else. Simply returning from a function or throwing an exception is not enough to stop the destructor from working.
This design is a bit flawed as writing to the database is an operation that can fail, and an exception from the destructor is a pretty bad idea.
source to share