473,657 Members | 3,021 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 1768
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.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting

Jul 23 '05 #2
"Dietmar Kuehl" <di***********@ yahoo.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.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
3489
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? Is this because there could be an exception thrown when the code creates a std::exception? I would assume that is not the case. However, if I want to create a new exception class, derived from std::exception (say MyException) then how can I...
11
3805
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. Thaks.
4
1734
by: JSheble | last post by:
If an exception occurs or is thrown in my constructor, what does the constructor actually return? A null?
8
1808
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 world can the destructor of a object that does not exist get called! Here is the MSDN2 document: Code authored in Visual C++ and compiled with /clr will run a type's destructor for the following reasons: ....
1
2801
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 exception. However, how can we make the interface easy to use correctly and hard to use incorrectly? Client may forget/ ignore from having a try...catch block whenever they call the constructor. Is there any way we can prevent this from happen?
3
3399
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 exception constructors? I've noticed that, f.ex., ArgumentException accepts null arguments without raising ArgumentNullException. Obviously, if nothing is to be supplied to the exception constructor, the default constructor should
23
7228
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
2909
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
1539
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
2364
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. Exception in Base(): "Going down (B can't be construced properly)!" (the exception has now been dealt with).
0
8384
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8302
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8820
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8499
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7314
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4150
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2726
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 we have to send another system
2
1601
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.