Re: is such exception handling approach good?
- From: ajk <ak@xxxxxxxxxxxx>
- Date: Fri, 21 Dec 2007 23:17:16 +0800
On Fri, 21 Dec 2007 04:44:01 -0800, George
<George@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?
thanks in advance,
George
it sounds as if you are doing some stuff in some constructor...
it is normally not a good idea to do operations in the ctor that could
cause an exception. the reason for this is that if an exception is
ever thrown in your ctor you end up with an invalid object. therefore
it is better to have some other method to initialize such with and
handle a failure outside the ctor like bool init() or something.
hth/ajk
.
- Follow-Ups:
- Re: is such exception handling approach good?
- From: Larry Smith
- Re: is such exception handling approach good?
- From: Alex Blekhman
- 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: A question about IShellLink interface and the COM object.
- Next by Date: Re: is such exception handling approach good?
- Previous by thread: Re: is such exception handling approach good?
- Next by thread: Re: is such exception handling approach good?
- Index(es):
Relevant Pages
|