Reputation: 2621
In the following code, I use a wrapper object to temporarily store some stuff from a db in memory. My question is simple:
Can I be sure that the destructor is called? I am particularly worried about cases where
a) testCondition
is true and the function returns early from an inner scope of the scope in which tempObj
was constructed
b) some runtime error occurs during the execution of this function (which is caught at a higher level)
(As a side question: is this a good way to temporarily store some data? In my application, someFunc()
is a 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
}
Upvotes: 3
Views: 1162
Reputation: 960
Yes, destructor will be called. Every object, created on stack will be correctly destroyed if you early return. If exception is thrown, destructor will be called after program execution arrived to the catch block.
Upvotes: 2
Reputation: 254411
The destructor of an automatic object will be called when the program leaves the object's scope. This includes returning from the function (early or otherwise), and leaving via an exception - as long as the exception is handled. In the case of an exception, it's called during stack unwinding before the exception is handled.
It might not be called in some cases, including:
longjmp
; this gives undefined behaviour;exit
, or raising a signal that causes termination).Upvotes: 6
Reputation: 40613
The destructor will be called unless the program blows up due to a seg fault or a power outage or whatever. Simply returning early from a function or throwing an exception is not enough to stop the destructor running.
This design is a bit flawed though, since writing to a database is an operation that could fail, and throwing an exception from a destructor is a pretty bad idea.
Upvotes: 2