473,503 Members | 1,697 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

exception in a constructor

It's a common practice that you throw an exception in a constructor
when the invariant of the class is not met. But what if it's combined
with auto_ptr? I mean:

#include <memory>
using namespace std;

struct S
{
S(int i) { if (i < 0) throw "oops"; }
};

int main()
try
{
auto_ptr<S> ap(new S(-1)); // A
}
catch (...)
{
}

Statement A can be considered step by step like this:
(1) raw memory is allocated by ::operator new(sizeof(S))
(2) the memory is initialized by S::S(int)
(3) an auto_ptr is constructed pointing to the memory
But you see an exeption is thrown at step (2) and auto_ptr is
*not* constructed, which means ~auto_ptr is not called.
The net result is memory leak, of course.
What is a proper way to solve this kind of problem?
Let's not consider the possibility of bad_alloc. (If a bad_alloc
is thrown, there's no leak at least.)

--
ES Kim
Jul 23 '05 #1
4 1751
ES Kim wrote:
auto_ptr<S> ap(new S(-1)); // A Statement A can be considered step by step like this:
(1) raw memory is allocated by ::operator new(sizeof(S))
(2) the memory is initialized by S::S(int)
(3) an auto_ptr is constructed pointing to the memory
But you see an exeption is thrown at step (2) and auto_ptr is
*not* constructed, which means ~auto_ptr is not called.
The net result is memory leak, of course.
The people creating the C++ standard thought of this: if an exception
is thrown during step 2, all members constructed so far are destroyed
and then 'operator delete()' is called appropriately (i.e., if you
used a placement form of new, a corresponding placement delete would
be called).
What is a proper way to solve this kind of problem?
You don't care about it because it is not your concern: it is the
compiler implementers concern.
Let's not consider the possibility of bad_alloc. (If a bad_alloc
is thrown, there's no leak at least.)


Nor is there if the constructor of the object throws an exception.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting

Jul 23 '05 #2
"Dietmar Kuehl" <di***********@yahoo.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
ES Kim wrote:
auto_ptr<S> ap(new S(-1)); // A

Statement A can be considered step by step like this:
(1) raw memory is allocated by ::operator new(sizeof(S))
(2) the memory is initialized by S::S(int)
(3) an auto_ptr is constructed pointing to the memory
But you see an exeption is thrown at step (2) and auto_ptr is
*not* constructed, which means ~auto_ptr is not called.
The net result is memory leak, of course.


The people creating the C++ standard thought of this: if an exception
is thrown during step 2, all members constructed so far are destroyed
and then 'operator delete()' is called appropriately (i.e., if you
used a placement form of new, a corresponding placement delete would
be called).


That's reassuring, and I found the relevent phrase in the Standard.
Thank you.

--
ES Kim
Jul 23 '05 #3
"ES Kim" <no@spam.mail> wrote in message
news:d0**********@news1.kornet.net...
struct S
{
S(int i) { if (i < 0) throw "oops"; }
};

int main()
try
{
auto_ptr<S> ap(new S(-1)); // A
}
catch (...)
{
}

Statement A can be considered step by step like this:
(1) raw memory is allocated by ::operator new(sizeof(S))
(2) the memory is initialized by S::S(int)
(3) an auto_ptr is constructed pointing to the memory
Once step (2) throws, step (3) never happens, and the system calls steps
(1x)
(1x) raw memory is de-allocated by ::operator delete(void*)

Please note that the system does NOT call (2x) because (2) did not run to
completion
(2x) the memory is de-initialized by S::~S()

However, if class S had member variables and the initialization list ran to
completion and it was the constructor body that threw an exception, then
rest assured that the system will call the destructors of the member
variables constructed till the exception was thrown. If S had a base class,
then I'm not sure if the destructor of the base class would get called, but
I imagine it would because it is kind of like a member variable.

Note that if there was a class S::operator new, the system would call that
instead of the global operator new, and S::operator delete.
But you see an exeption is thrown at step (2) and auto_ptr is
*not* constructed, which means ~auto_ptr is not called.
The net result is memory leak, of course.
What is a proper way to solve this kind of problem?
Let's not consider the possibility of bad_alloc. (If a bad_alloc
is thrown, there's no leak at least.)


Your code is fine.

Jul 23 '05 #4
There's an MSDN article that explains this issue quite well:
http://msdn.microsoft.com/library/de...deep090799.asp

Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3480
by: Pierre Rouleau | last post by:
The std::exception class defined in the Standard C++ <exception> header specifies that the constructors could throw any exception becuase they do not have a throw() specification. Why is that? ...
11
3784
by: Ivan A. | last post by:
Hi Is there any method to change System. Exception. Message property in derived exception's constructor? I need runtime class' information to initialize this property, but it's readonly. ...
4
1723
by: JSheble | last post by:
If an exception occurs or is thrown in my constructor, what does the constructor actually return? A null?
8
1788
by: JAL | last post by:
According to MSDN2, if a managed class throws an exception in the constructor, the destructor will be called. If an exception is thrown in the constructor the object never existed so how in the...
1
2788
by: yancheng.cheok | last post by:
Hi all, According to "How can I handle a constructor that fails?" in http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.2, whenever there is a constructor fail, we will throw...
3
3389
by: matko | last post by:
This is a long one, so I'll summarize: 1. What are your opinions on raising an exception within the constructor of a (custom) exception? 2. How do -you- validate arguments in your own...
23
7198
by: TarheelsFan | last post by:
What happens whenever you throw an exception from within a constructor? Does the object just not get instantiated? Thanks for replies.
4
2894
by: Sunil Varma | last post by:
Hi, Here is a piece of code where the constructor throws an exception. class A { int n; public: A() try{
5
1523
by: Vijay | last post by:
Hi All, I am not able to figure out what exactly happening in below code. what is control flow. Can anyone clear my confusion? Code: class A { public: A(){cout<<"In Constructor\n";}
11
2349
by: Peter Jansson | last post by:
Dear newsgroup, In the following code, it looks as though the exception thrown in the constructor is not caught properly. I get this output: ---- standard output ---- Base() constructor....
0
7273
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7322
jinu1996
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...
1
6982
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...
0
7451
tracyyun
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...
0
5572
agi2029
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,...
0
3161
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1501
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
374
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.