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, -
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
6 1487
This code is never safe.
When an exception is thrown, the current stack frame is not cleaned up. That is, the destructors for the local objects are not called.
That is, an exception is a hard go-to-the-catch-block.
This means you can't just willy-nilly use exceptions. You need to design for them. In your example, the two stack objects should be allocated on the heap. Then inside the function you catch the exception, delete the objects, and then rethrow it now that the local stack frame is cleaned up: -
void func()
-
{
-
Class1* inst1 = 0;
-
Class2* inst2 = 0;
-
try
-
{
-
inst1 = new Class1;
-
inst2 = new Class2;
-
-
// some operations
-
throw 25;
-
}
-
catch (...)
-
{
-
delete inst1;
-
delete inst2;
-
throw; //rethrow the excpetion
-
}
-
return;
-
}
-
Thanks weaknessforcats,
1.
I think we are talking about different things. :-)
This is your code, -
Class1* inst1 = 0;
-
Class2* inst2 = 0;
-
inst1 = new Class1;
-
inst2 = new Class2;
-
This is my code -
Class1 inst1;
-
Class2 inst2;
-
My object instances are on the stack, but your object instances are on the heap (only pointer on stack). I think in my situation, it is safe and does not leak any resources if there are any exception thrown when stack unwinding makes us go out of the stack, the destructor is automatically called (since when we are out of the current stack during stack unwinding, the lifecycle of inst1 and inst2 expired and their destructors are called).
2. what do you mean the stack is not cleaned up?
I think in my situation the destructors are called since during stack unwinding, the lifecycle of objects' instances are expired and their destructors should be called.
This code is never safe.
When an exception is thrown, the current stack frame is not cleaned up. That is, the destructors for the local objects are not called.
Please feel free to correct me if I am wrong.
regards,
George
I think in my situation the destructors are called since during stack unwinding, the lifecycle of objects' instances are expired and their destructors should be called.
Yes, I was incorrect. I meant to say that heap allocations are not unwound in the current stack frame. Stack objects will have destructors call provided the exception is caught. Otherwise, they're not. Heap allocations will remain unless you delete them.
I so seldom use stack objects because of the risks associated with them when used as function arguments. It's too easy for a reference or an address of one of these stack objects to become a member of another object that is returned. Later, that reference or address may be no good and crash the program.
Thanks weaknessforcats,
I understand your points now. I think using auto_ptr can solve this issue when you forget to call delete explicitly, right?
Do you agree using auto_ptr and put cleanup code in destructor can solve all the issues?
Yes, I was incorrect. I meant to say that heap allocations are not unwound in the current stack frame. Stack objects will have destructors call provided the exception is caught. Otherwise, they're not. Heap allocations will remain unless you delete them.
I so seldom use stack objects because of the risks associated with them when used as function arguments. It's too easy for a reference or an address of one of these stack objects to become a member of another object that is returned. Later, that reference or address may be no good and crash the program.
regards,
George
I think using auto_ptr can solve this issue when you forget to call delete explicitly, right?
Do you agree using auto_ptr and put cleanup code in destructor can solve all the issues?
Avoid using auto_ptr. It doesn't work like you think. See Effective STL by Scott Meyers Item #8.
However, the approach is correct. Use a smart pointer with built-in reference counting. There is an article I wrote in the Howtos for C++ on Handle classes. In that article is a template for a reference-counted handle that you are free to use in your applications. It works very like the shared_ptr that's coming out with the new C++.
Thanks weaknessforcats,
1.
Avoid using auto_ptr. It doesn't work like you think. See Effective STL by Scott Meyers Item #8.
Why in my sample, I can not use auto_ptr to solve this issue to make sub-components' destructor called automatically? More descriptions please?
2. I am interested in your article, could you post a link please?
However, the approach is correct. Use a smart pointer with built-in reference counting. There is an article I wrote in the Howtos for C++ on Handle classes. In that article is a template for a reference-counted handle that you are free to use in your applications. It works very like the shared_ptr that's coming out with the new C++.
regards,
George
Sign in to post your reply or Sign up for a free account.
Similar topics
by: adi |
last post by:
Dear all,
This is more like a theoretical or conceptual question:
which is better, using exception or return code for
a .NET component?
I had created a COM object (using VB6), which uses...
|
by: cody |
last post by:
public DateTime Value
{
get
{
try
{
return new DateTime(int.Parse(tbYear.Text), int.Parse(tbMonth.Text),
int.Parse(tbDay.Text));
}
catch (FormatException)
|
by: Abelardo Vacca |
last post by:
Hello,
I am currently in the process of switching our application to a N-Tier model
with .NET.
One of the aspects we want ot get right from the start not to worry about it
after is the...
|
by: Frank Puck |
last post by:
Meanwhile there are at least 8 years that compilers exist,
which provide a working implementation of C++ Exception Handling.
Has anything changed meanwhile?
From my point of view nothing has...
|
by: Julia |
last post by:
Hi I have a system which composed from 2 different components
1.MailSender
2.MailReciever
the Name of my system is JuliaSystem
|
by: craig |
last post by:
I am wondering if there are some best practices for determining a strategy
for using try/catch blocks within an application.
My current thoughts are:
1. The code the initiates any high-level...
|
by: Bruce One |
last post by:
I am developing a new project in which we should have a good Exception
Handling. Ive seen there is a Exception Handling App Block in Enterprise
Library, also I could use the Try-Catch structure...
|
by: Rex |
last post by:
Re: Looking for Tips/Writeup on overall approach to Exception
Processing
Hi All - I am fairly new to C# and am wondering how to best implement
(overall) Exception Processing within my...
|
by: George2 |
last post by:
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...
|
by: eliben |
last post by:
Python provides a quite good and feature-complete exception handling
mechanism for its programmers. This is good. But exceptions, like any
complex construct, are difficult to use correctly,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |