Re: is such exception handling approach good?
- From: Abhishek Padmanabh <abhishek.padmanabh@xxxxxxxxx>
- Date: Fri, 21 Dec 2007 05:05:16 -0800 (PST)
On Dec 21, 5:44 pm, George <Geo...@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
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,
[Code]
void func()
{
Class1 inst1;
Class2 inst2;
... // some operations
return;}
[/Code]
Does above code always safe? Are there any potential risks to leak resources?
Yes, it is safe. But it is hard to say always because there isn't an
exact problem that you have defined. From the extent of your problem
definition, it will be safe and there are no potential risks.
Congratulations! you have just discovered RAII.
.
- Follow-Ups:
- Re: is such exception handling approach good?
- From: George
- Re: is such exception handling approach good?
- References:
- is such exception handling approach good?
- From: George
- is such exception handling approach good?
- Prev by Date: Re: Reference are always lvalue?
- Next by Date: Re: Single instance issue
- Previous by thread: is such exception handling approach good?
- Next by thread: Re: is such exception handling approach good?
- Index(es):
Relevant Pages
|