473,387 Members | 1,530 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Constructor throws?

According to the FAQ, the best way to inform a class user of an error
that occurs inside a constructor is to throw an exception. My question
is, what happens when an object is instantiated using 'new', and the
constructor throws after 'new' allocates memory for that object? Will
the memory leak? Thanks.

Jun 20 '07 #1
4 3098
in*************@gmail.com wrote:
According to the FAQ, the best way to inform a class user of an error
that occurs inside a constructor is to throw an exception. My question
is, what happens when an object is instantiated using 'new', and the
constructor throws after 'new' allocates memory for that object? Will
the memory leak? Thanks.
I think, it's a quality of implementation issue. Clause [5.3.4/8] _allows_
the implementation to do the right thing:

A new-expression obtains storage for the object by calling an allocation
function (3.7.3.1). If the newexpression terminates by throwing an
exception, it may release storage by calling a deallocation function
(3.7.3.2) ...

That said, I would hope (and assume) that you will have a hard time finding
an implementation where memory leaks in this case.

You could run the following and monitor its storage usage with OS tools:

#include <iostream>

struct X {

char data [8192];

X ( void ) {
throw ( 1 );
}

};

int main ( void ) {
while ( true ) {
try {
X* x_ptr = new X;
}
catch ( ... ) {
std::cout << '.';
}
}
}
Best

Kai-Uwe Bux
Jun 20 '07 #2
On Jun 21, 12:12 am, indrawati.ya...@gmail.com wrote:
According to the FAQ, the best way to inform a class user of an error
that occurs inside a constructor is to throw an exception. My question
is, what happens when an object is instantiated using 'new', and the
constructor throws after 'new' allocates memory for that object? Will
the memory leak?
If it is a non-placement new, the global operator delete
function will be called for the memory. (Watch out for memory
that was allocated within the constructor before throwing,
however.) If it is a placement new, and a corresponding
placement operator delete function exists, it will be called.
If no corresponding placement operator delete function has been
declared, the compiler assumes that it isn't necessary. (For
some reason, the standard defines a no-op placement operator
delete function for the standard placement new, rather than
count on the fact that if there is no corresponding placement
operator delete function, the compiler will do nothing. I
suppose it does prevent the user from accidentally defining one
that does something, but I'll admit that users accidentally
defining a placement delete that shouldn't have been defined has
not been a major cause of error in the code that I've seen.)

--
James Kanze (GABI Software, from CAI) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 21 '07 #3

indrawati.ya...@gmail.com wrote:
According to the FAQ, the best way to inform a class user of an error
that occurs inside a constructor is to throw an exception. My question
is, what happens when an object is instantiated using 'new', and the
constructor throws after 'new' allocates memory for that object? Will
the memory leak? Thanks.

the memory is freed automatically. This is easy to check.

Using exceptions to terminate constructors is very elegant.
Think about the horrible solutions people invented before exceptions
were introduced.
Now you can have a fallible resource allocation inside a constructor.
Some suggestions:

* perform only a single resource allocation inside a constructor.
If you perform more than one allocation inside a constructor you will
have to deal with cleanup yourself in case of one of the allocation
fails. Remember that destructors are only called for successfully
constructed objects (which have not been aborted by a exception
thrown). If you throw in a constructor of a class which has base-
classes or member-classes, the destructors for the successfully
constructed base-classes or member-classes are called.
* resource allocation is everything which is paired:
Creating a window/destroying a window
Opening a file/closing a file
mapping a file/unmapping a file
setting a handler/restoring the original handler
showing a window/hiding a window
creating a (bitmap) handle, destroying this (bitmap) handle
* throw an exception if the matching allocation fails. This exception
should contain all necessary information -- e.g. system error
information to give rich error information
* chain such single allocation classes into more complex classes using
base-class/member class relationships

Jun 21 '07 #4
Kai-Uwe Bux wrote:
in*************@gmail.com wrote:
>According to the FAQ, the best way to inform a class user of an error
that occurs inside a constructor is to throw an exception. My question
is, what happens when an object is instantiated using 'new', and the
constructor throws after 'new' allocates memory for that object? Will
the memory leak? Thanks.

I think, it's a quality of implementation issue. Clause [5.3.4/8] _allows_
the implementation to do the right thing:

A new-expression obtains storage for the object by calling an allocation
function (3.7.3.1). If the newexpression terminates by throwing an
exception, it may release storage by calling a deallocation function
(3.7.3.2) ...
Correcting myself: it's not a quality of implementation issue. I had missed
clause [5.3.4/17]:
If any part of the object initialization described above terminates by
throwing an exception and a suitable deallocation function can be found,
the deallocation function is called to free the memory in which the object
was being constructed, after which the exception continues to propagate in
the context of the newexpression. If no unambiguous matching deallocation
function can be found, propagating the exception does not cause the
object?s memory to be freed. [Note: This is appropriate when the called
allocation function does not allocate memory; otherwise, it is likely to
result in a memory leak. ]
Best

Kai-Uwe Bux

Jun 22 '07 #5

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

Similar topics

18
by: Matt | last post by:
I try to compare the default constructor in Java and C++. In C++, a default constructor has one of the two meansings 1) a constructor has ZERO parameter Student() { //etc... } 2) a...
3
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? ...
6
by: Fred Zwarts | last post by:
Hello, I am trying to debug some complex debug code. In order to track the use of dynamically allocated memory, I replaced the standard global new and delete operators. (Not for changing the...
5
by: Zoltan Hernyak | last post by:
Hi, see my classes: public class One { public One(string s) { .... } } public class Two:One
19
by: Andrew J. Marshall | last post by:
I want to create a class that must receive a parameter when instantiated. In other words, I do not want it to have a "Public Sub New()". 1) Does VB.NET create a default public constructor if I do...
8
by: =?Utf-8?B?cnZtYWNjb3VudA==?= | last post by:
It seems the static constructor is supposed to be called, ONLY once for a particular type. If that's the case, why does the following code throws an exception? using System; using...
12
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? ...
10
by: George2 | last post by:
Hello everyone, Here is a sample from Dr. Dobb C++. In the analysis, the code is bad below. But I do not think the code is bad, 1. if bad_alloc is thrown in new int, we just catch it and...
4
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{
3
by: vaclavpich | last post by:
Hi I've a question about constructors and exceptions. //************************************************************ class CObject { public: // ctor CObject(); // dtor ~ CObject();
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
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...
0
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...
0
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,...
0
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...
0
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,...

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.