473,563 Members | 2,709 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exceptions & Constructors

The constructor in MyClass instantiates many objects pointers through
'new', I would like to implement a way to make sure that the object
has been allocated in memory by catch(ing) the bad_alloc exception
error, but this means that I have to throw this error back from
MyClass constructor, how can I avoid this?

Thanks folks!

Jul 30 '07 #1
14 1590
On 2007-07-30 13:15, ja******@gmail. com wrote:
The constructor in MyClass instantiates many objects pointers through
'new', I would like to implement a way to make sure that the object
has been allocated in memory by catch(ing) the bad_alloc exception
error, but this means that I have to throw this error back from
MyClass constructor, how can I avoid this?
Sure, add a flag to the class that tells if the object was constructed
correctly:

class Foo {
int* ptrarr[16];
public:
bool correct;
Foo() correct(true) {
try {
for (size_t i = 0; i < 16; ++i)
ptrarr[i] = new int();
} catch(bad_alloc &) {
correct = false;
}
}
};

int main() {
Foo f;
if (f.correct == false) {
// Opps, failed to allocate
}
}

--
Erik Wikström
Jul 30 '07 #2
<ja******@gmail .comwrote in message
news:11******** **************@ l70g2000hse.goo glegroups.com.. .
The constructor in MyClass instantiates many objects pointers through
'new', I would like to implement a way to make sure that the object
has been allocated in memory by catch(ing) the bad_alloc exception
error, but this means that I have to throw this error back from
MyClass constructor, how can I avoid this?
Well, what do you want your code to do on failure?

Consider:

class Foo
{
// ...
};

int main()
{
Foo Bar;
}

What do you want to happen if Bar can not be instantized because of bad
allocation inside of Foo's constructor? And how do you want to check if it
was successful?

Some things I can think of off the top of my head.

1. Have Foo contain a private bool variable stating if all pointers have
been instantized correctly with newed instances. Alternative to this, is to
check any of the pointers itself for a NULL value which you would set in the
constructor if initializaiton of the variables failed. Foo could have a
method returning if it was initalized or not. Foo could have it's internal
methods checking initialzation.

2. Have Foo created only by a factory (I.E returning a pointer). If Foo can
not be instantized, the factory returns NULL which mainline can check.

3. Do nothing and have new's throw propogate up to mainline

I could think of a few other methods depending on what you would want done.
It is not a good thing to have an instance floating around that was not
properly instantized. How are you going to provent this if you don't allow
new's throw to propogate? How do you WANT to prevent it?
Jul 30 '07 #3
Erik Wikström wrote:
On 2007-07-30 13:15, ja******@gmail. com wrote:
>The constructor in MyClass instantiates many objects pointers through
'new', I would like to implement a way to make sure that the object
has been allocated in memory by catch(ing) the bad_alloc exception
error, but this means that I have to throw this error back from
MyClass constructor, how can I avoid this?

Sure, add a flag to the class that tells if the object was constructed
correctly:

class Foo {
int* ptrarr[16];
public:
bool correct;
Foo() correct(true) {
try {
for (size_t i = 0; i < 16; ++i)
ptrarr[i] = new int();
} catch(bad_alloc &) {
correct = false;
}
}
};

int main() {
Foo f;
if (f.correct == false) {
// Opps, failed to allocate
}
}
That code leaks if it fails. Should you not have to delete all of them
or at lease assign a null pointer ?
Jul 30 '07 #4
On 2007-07-30 14:24, Gianni Mariani wrote:
Erik Wikström wrote:
>On 2007-07-30 13:15, ja******@gmail. com wrote:
>>The constructor in MyClass instantiates many objects pointers through
'new', I would like to implement a way to make sure that the object
has been allocated in memory by catch(ing) the bad_alloc exception
error, but this means that I have to throw this error back from
MyClass constructor, how can I avoid this?

Sure, add a flag to the class that tells if the object was constructed
correctly:

class Foo {
int* ptrarr[16];
public:
bool correct;
Foo() correct(true) {
try {
for (size_t i = 0; i < 16; ++i)
ptrarr[i] = new int();
} catch(bad_alloc &) {
correct = false;
}
}
};

int main() {
Foo f;
if (f.correct == false) {
// Opps, failed to allocate
}
}

That code leaks if it fails. Should you not have to delete all of them
or at lease assign a null pointer ?

Actually it does not even compile, I forgot the : in the initialisation
list and have not included the headers for bad_alloc etc. It was more to
show the OP the general idea then to give him/her code that worked, as
an example I don't expect that the OP has an array of pointers but
rather a number of pointers, which should then be initialised to null in
the initialisation list before allocating memory with new. Or perhaps
using some kind of smart pointer.

--
Erik Wikström
Jul 30 '07 #5
Roy
On Jul 30, 5:52 pm, Erik Wikström <Erik-wikst...@telia. comwrote:
On 2007-07-30 14:24, Gianni Mariani wrote:
Erik Wikström wrote:
On 2007-07-30 13:15, jalqa...@gmail. com wrote:
The constructor in MyClass instantiates many objects pointers through
'new', I would like to implement a way to make sure that the object
has been allocated in memory by catch(ing) the bad_alloc exception
error, but this means that I have to throw this error back from
MyClass constructor, how can I avoid this?
Sure, add a flag to the class that tells if the object was constructed
correctly:
class Foo {
int* ptrarr[16];
public:
bool correct;
Foo() correct(true) {
try {
for (size_t i = 0; i < 16; ++i)
ptrarr[i] = new int();
} catch(bad_alloc &) {
correct = false;
}
}
};
int main() {
Foo f;
if (f.correct == false) {
// Opps, failed to allocate
}
}
That code leaks if it fails. Should you not have to delete all of them
or at lease assign a null pointer ?

Actually it does not even compile, I forgot the : in the initialisation
list and have not included the headers for bad_alloc etc. It was more to
show the OP the general idea then to give him/her code that worked, as
an example I don't expect that the OP has an array of pointers but
rather a number of pointers, which should then be initialised to null in
the initialisation list before allocating memory with new. Or perhaps
using some kind of smart pointer.

--
Erik Wikström
the lost : in the initialization list had me confused ! :-( , thanks
for clearing this up !
What you have suggested is an elegant way of handling an exception ,
what else is bool used for ?

Jul 30 '07 #6
On 2007-07-30 15:09, Roy wrote:
On Jul 30, 5:52 pm, Erik Wikström <Erik-wikst...@telia. comwrote:
>On 2007-07-30 14:24, Gianni Mariani wrote:
Erik Wikström wrote:
On 2007-07-30 13:15, jalqa...@gmail. com wrote:
The constructor in MyClass instantiates many objects pointers through
'new', I would like to implement a way to make sure that the object
has been allocated in memory by catch(ing) the bad_alloc exception
error, but this means that I have to throw this error back from
MyClass constructor, how can I avoid this?
>Sure, add a flag to the class that tells if the object was constructed
correctly:
>class Foo {
int* ptrarr[16];
public:
bool correct;
Foo() correct(true) {
try {
for (size_t i = 0; i < 16; ++i)
ptrarr[i] = new int();
} catch(bad_alloc &) {
correct = false;
}
}
};
>int main() {
Foo f;
if (f.correct == false) {
// Opps, failed to allocate
}
}
That code leaks if it fails. Should you not have to delete all of them
or at lease assign a null pointer ?

Actually it does not even compile, I forgot the : in the initialisation
list and have not included the headers for bad_alloc etc. It was more to
show the OP the general idea then to give him/her code that worked, as
an example I don't expect that the OP has an array of pointers but
rather a number of pointers, which should then be initialised to null in
the initialisation list before allocating memory with new. Or perhaps
using some kind of smart pointer.

--
Erik Wikström

the lost : in the initialization list had me confused ! :-( , thanks
for clearing this up !
What you have suggested is an elegant way of handling an exception ,
what else is bool used for ?
For storing anything that can only have two different values. It is not
uncommon to get into a situation where you want to check something, and
the answer can then either be true or false, such as is a container
empty? Does the container contain a specific element? In all those cases
bool is a suitable return type.

It is also used to check conditions in loops and control-statements, the
==, !=, <, >, <=, and >= operators (along with some I probably forgot)
all return a value of type bool (or something convertible to bool). As
an example a while-loop loops as long as the condition is true, so an
infinite loop can be written like this:

while (true)
{
// ...
}

--
Erik Wikström
Jul 30 '07 #7
On Jul 30, 12:15 pm, "jalqa...@gmail .com" <jalqa...@gmail .comwrote:
The constructor in MyClass instantiates many objects pointers through
'new', I would like to implement a way to make sure that the object
has been allocated in memory by catch(ing) the bad_alloc exception
error, but this means that I have to throw this error back from
MyClass constructor, how can I avoid this?
It's worth considering the role of the subordinate object ...
I know you said you wanted to avoid exceptions emerging from your
MyClass ctor, but if the subordinate objects are really an
indivisible part of the MyClass object, ie a MyClass doesn't make
any sense without them and isn't usable unless they are there,
then letting the exception propagate out of the ctor makes sense
and can make your code a lot cleaner. Eg:

MyClass x;
x.good_I_must_h ave_a_fully_con sed_MyClass_now ();

It's worth bearing in mind that many deem propagating exceptions from
ctors to be the correct way of handling this sort of situation, and
view setting a 'constructed ok' flag as a hack best avoided.

Alternatively if the MyClass instance is usable without a subordinate,
then you can absorb the bad_alloc in the MyClass ctor and flag the
absence of the subordinate object with a null pointer:

MyClass x;
if (x.ptr_to_nice_ to_have != 0) // nb should encapsulate properly
x.some_method_u sing_nice_to_ha ve();
Cheers.

Jul 30 '07 #8
On Jul 30, 2:39 pm, tragomaskhalos <dave.du.verg.. .@logicacmg.com >
wrote:
>
Alternatively if the MyClass instance is usable without a subordinate,
then you can absorb the bad_alloc in the MyClass ctor and flag the
absence of the subordinate object with a null pointer:
Er, or indeed use a nothrow new and get a null ptr without having to
worry
about bad_alloc at all.

But to amplify my previous point, exceptions are your friends: too
often
people want to catch exceptions as soon as they are thrown and
convert
them into flags or error codes, which obviates the whole purpose of
them,
which is to free a program's logic from endlessly having to check
niggling
little will-only-happen-in-extremely-rare-and-bad-situation failures.

Jul 30 '07 #9

<ja******@gmail .coma écrit dans le message de
news:11******** **************@ l70g2000hse.goo glegroups.com.. .
The constructor in MyClass instantiates many objects pointers through
'new', I would like to implement a way to make sure that the object
has been allocated in memory by catch(ing) the bad_alloc exception
error, but this means that I have to throw this error back from
MyClass constructor, how can I avoid this?

Thanks folks!
If you mind, a static function could be used... returning NULL in case of
failure...

Just like that :

template <typename Tstatic Pile<T* createPile(int sz)
{
Pile<T* pp;
try
{
pp = new Pile<T>(sz);
return pp;
}
catch (std::bad_alloc &)
{
try
{
// clearing what can be cleared ...
// ...
// deleting the instance : the destructor has to be sure
// (may be hard to do...)
pp->~Pile<T>();
}
catch (std::exception & e)
{
// nothing to do
}
return NULL;
}
}

But remember what Alf P. Steinbach said !!

Xavier
Jul 30 '07 #10

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

Similar topics

5
1368
by: John | last post by:
Hi, In my years as a VB programmer, I have settled into this pattern of creating collections classes, with an AddNew() method. AddNew() validates the parameters, instantiates the object, adds it to the collection, and returns it. The AddNew() method was used to get around the lack of a constructor in VB classes. Now I was just about to...
8
3566
by: Shane Groff | last post by:
I know this is a recurring discussion (I've spent the last 3 days reading through threads on the topic), but I feel compelled to start it up again. After reading through the existing threads, I find myself convinced that exceptions are a better mechanism, for example because constructors and operators can't return errors, and code that...
10
1762
by: Brian Folke Seaberg | last post by:
I was recently browsing a couple of C++ books at the local bookstore. One book called throwing exceptions from constructors a "dubious practice." Another book recommended not throwing exceptions from constructors due to the fact that the destructor for the object being constructed will not be executed and that as a result any resources...
21
4398
by: mihai | last post by:
People say that is a bad technique to throw exception from constructors; and that the solution would be to create a function _create_ to initialize an object. What about copy constructors? How can we avoid throwing exceptions? If we already have an abject witch was initialized wit _create_ we will be forced to call create in copy...
4
2373
by: KC | last post by:
Greeting all! I have a problem that I'm hoping will be of interest to others here, and maybe a solution will crop up. I appoligize for the message's length. Now, I'm new to C# and .NET, so I am developing an application during my learning phase. Because of this, I'm trying to use as many *features* as is reasonable. Some may be more...
16
2148
by: Einar Høst | last post by:
Hi, I'm getting into the Trace-functionality in .NET, using it to provide some much-needed logging across dlls in the project we're working on. However, being a newbie, I'm wondering if some more experienced loggers can provide me with some ideas as to how to log in a simple yet flexible manner. For instance, I'd like the code to be as...
5
1880
by: tryptik | last post by:
All- I have heard differing points of view on whether or not constructors should throw. I am working on a library, and I need to know if it is bad form for a consturctor to throw. Thanks -J
24
4918
by: usenet | last post by:
I am unable to catch floating exceptions (e.g. divide by 0 or 0/0) using the standard exceptions defined in stdexcept. What is the recommended way to catch such exceptions? Thanks, Song
0
7664
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...
0
7583
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...
1
7638
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...
0
7948
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6250
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...
1
5484
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...
0
3642
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...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2082
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

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.