Re: is such exception handling approach good?

Tech-Archive recommends: Speed Up your PC by fixing your registry



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.
.



Relevant Pages

  • Re: is such exception handling approach good?
    ... Suppose I have some objects created on local function stack. ... exception handling code in the function for resource free purpose, ... rely on destructor to free resources if exception occurs, that is, ...
    (microsoft.public.vc.language)
  • is such exception handling approach good?
    ... Suppose I have some objects created on local function stack. ... destructor. ... exception handling code in the function for resource free purpose, ... rely on destructor to free resources if exception occurs, that is, ...
    (microsoft.public.vc.language)
  • Re: is such exception handling approach good?
    ... No exception from this rule that I know of (no pun ... For the object pointed by smart pointer, ... Free that resource in the destructor. ... For resources other than the heap memory, you would use other classes to ...
    (microsoft.public.vc.language)
  • Re: resource leak in destructor?
    ... review both of them are good code -- no resource leak, ... exception in function FreeResources please? ... // free some resources, but the operation may throw exception ...
    (microsoft.public.vc.language)
  • Re: resource leak in destructor?
    ... review both of them are good code -- no resource leak, ... // free some resources, but the operation may throw exception ...
    (microsoft.public.vc.language)