G
George2
Hello everyone,
Suppose I have some objects created on local function stack (not on
heap). And I allocate and free all the related resources in the
constructor and destructor (e.g. memory and file handles). And I do
not implement explicit exception handling code in the function for
resource free purpose, and simply rely on destructor to free resources
if exception occurs, that is,
1. when exception occurs and the exception triggers us to go out of
current function stack to the caller to find exception handlers;
2. since objects are allocated on local stack, when exception triggers
us to go out of current stack to its caller to find exception handler,
the lifecycle of local objects on local stack will expire, and its
related destructor will be invoked and free resources.
Pseudo code like this,
Does above code always safe? Are there any potential risks to leak
resources?
thanks in advance,
George
Suppose I have some objects created on local function stack (not on
heap). And I allocate and free all the related resources in the
constructor and destructor (e.g. memory and file handles). And I do
not implement explicit exception handling code in the function for
resource free purpose, and simply rely on destructor to free resources
if exception occurs, that is,
1. when exception occurs and the exception triggers us to go out of
current function stack to the caller to find exception handlers;
2. since objects are allocated on local stack, when exception triggers
us to go out of current stack to its caller to find exception handler,
the lifecycle of local objects on local stack will expire, and its
related destructor will be invoked and free resources.
Pseudo code like this,
Code:
void func()
{
Class1 inst1;
Class2 inst2;
... // some operations
return;
}
Does above code always safe? Are there any potential risks to leak
resources?
thanks in advance,
George