473,322 Members | 1,425 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,322 software developers and data experts.

throwing exception from constructor .

I read , FAQ : 17.4] How should I handle resources if my constructors
may throw exceptions?

Above faq says that use smart pointer in construcors . Because if
exception is thrown from constructor it's destructor is not run .So to
avoid memory lekage use smart pointer .
But if exception is thrown we can release resources in catch block . So
use of smart pointer is not must , we have this secnd option . Am i
right ?

Apr 6 '06 #1
11 11939
mangesh wrote:
I read , FAQ : 17.4] How should I handle resources if my constructors
may throw exceptions?

Above faq says that use smart pointer in construcors . Because if
exception is thrown from constructor it's destructor is not run .So to
avoid memory lekage use smart pointer .
But if exception is thrown we can release resources in catch block .
So use of smart pointer is not must , we have this secnd option . Am i
right ?


You can release in a catch block, unless you lose track of the resource
to be released. If it's a local object in the body of the construct,
how do you know its value to release in the catch block?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 6 '06 #2
mangesh wrote:
I read , FAQ : 17.4] How should I handle resources if my constructors
may throw exceptions?

Above faq says that use smart pointer in construcors . Because if
exception is thrown from constructor it's destructor is not run .So to
avoid memory lekage use smart pointer .
But if exception is thrown we can release resources in catch block . So
use of smart pointer is not must , we have this secnd option . Am i
right ?


Consider:
class ResourceHolder {
int* pointer1;
int* pointer2;
// prevent copy and assignment
ResourceHolder(const ResourceHolder&);
ResourceHolder& operator=(const ResourceHolder&);
public:
ResourceHolder() : pointer1(new int(1)), pointer2(new int(2)) {}
~ResourceHolder() {
delete pointer1;
delete pointer2;
}
}

The line:
ResourceHolder r;

Requires allocation of 2 ints, either of which could fail and throw an
exception. The problem is: which one failed?

If you change the constructor to include try catch:
ResourceHolder() : pointr1(0), pointer2(0) {
// if this throws, it's ok
pointer1 = new int(1);
try {
// if this throws, clean up pointer 1
pointer2 = new int(2);
} catch () {
delete pointer1;
}
}

That's starting to get a bit messy, imagine scaling that to 5 resources,
it's better to apply RAII to all resources, and just use a smart
pointer, even if it's just std::auto_ptr<int>.

It's much less error prone.

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Apr 6 '06 #3
can't we call destructor explicitly in catch block ?

Apr 6 '06 #4
mangesh wrote:
can't we call destructor explicitly in catch block ?


Yes you can.

The following should work just fine but in general it might be not
trivial to ensure that the destructor can be safely called for a
partially constructed object. E.g. in this case the initialization of
the pointers to 0 is crucial.

ResourceHolder() : pointer1(0), pointer2(0) {
try {
pointer1 = new int(1);
pointer2 = new int(2);
} catch(...) {
this->ResourceHolder::~ResourceHolder();
throw;
}
}

Apr 6 '06 #5
mangesh wrote:
can't we call destructor explicitly in catch block ?


It's not advisable to delete something that was not allocated. If
pointer1 fails allocation, and you call the destructor, you will delete
two objects that were not allocated. Of course, if the pointers were
initialised to 0, then calling delete on them is ok.

What do you have against auto_ptr? It does the job you require, with
neat and safe syntax. Use it.

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Apr 6 '06 #6
Ben Pope wrote:
mangesh wrote:
can't we call destructor explicitly in catch block ?


What do you have against auto_ptr? It does the job you require, with
neat and safe syntax. Use it.


auto_ptr as member is generally not advisable because of its odd copy
semantics. You can of course use it locally and then assign to the
actual member later:

auto_ptr<int> p1 = new int(1);
auto_ptr<int> p2 = new int(2);

// ... other stuff that might throw ...

pointer1 = p1.release();
pointer2 = p2.release();

Apr 6 '06 #7
Markus Schoder wrote:
Ben Pope wrote:
mangesh wrote:
can't we call destructor explicitly in catch block ?

What do you have against auto_ptr? It does the job you require, with
neat and safe syntax. Use it.


auto_ptr as member is generally not advisable because of its odd copy
semantics.


Not much more odd than a pointer, it won't get you into any more
trouble, besides, in my example I had disabled copying. This is fairly
common in classes that manage resources.

The point is that there are tools to help, the OP should use them.

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Apr 6 '06 #8
Ben Pope wrote:
Markus Schoder wrote:
Ben Pope wrote:
mangesh wrote:
can't we call destructor explicitly in catch block ?
What do you have against auto_ptr? It does the job you require, with
neat and safe syntax. Use it.


auto_ptr as member is generally not advisable because of its odd copy
semantics.


Not much more odd than a pointer, it won't get you into any more
trouble, besides, in my example I had disabled copying. This is fairly
common in classes that manage resources.


auto_ptr has a copy constructor that modifies the _source_. This is as
odd as it gets in my book.

Apr 6 '06 #9

"Markus Schoder" <a3*************@yahoo.de> wrote in message
news:11*********************@z34g2000cwc.googlegro ups.com...
Ben Pope wrote:
Markus Schoder wrote:
> Ben Pope wrote:
>> mangesh wrote:
>>> can't we call destructor explicitly in catch block ?
>> What do you have against auto_ptr? It does the job you require, with
>> neat and safe syntax. Use it.
>
> auto_ptr as member is generally not advisable because of its odd copy
> semantics.


Not much more odd than a pointer, it won't get you into any more
trouble, besides, in my example I had disabled copying. This is fairly
common in classes that manage resources.


auto_ptr has a copy constructor that modifies the _source_. This is as
odd as it gets in my book.


I agree. IMHO auto_ptr should never be used as a member in a class. No
matter how carefully you document the resulting behavior, when somebody
writes

y = x;

and it changes x, confusion if not disaster is likely to follow.

boost::shared_ptr doesn't have this problem.

Cy
Apr 7 '06 #10

Cy Edmunds wrote:
"Markus Schoder" <a3*************@yahoo.de> wrote in message
news:11*********************@z34g2000cwc.googlegro ups.com...
Ben Pope wrote:
Markus Schoder wrote:
> Ben Pope wrote:
>> mangesh wrote:
>>> can't we call destructor explicitly in catch block ?
>> What do you have against auto_ptr? It does the job you require, with
>> neat and safe syntax. Use it.
>
> auto_ptr as member is generally not advisable because of its odd copy
> semantics.

Not much more odd than a pointer, it won't get you into any more
trouble, besides, in my example I had disabled copying. This is fairly
common in classes that manage resources.


auto_ptr has a copy constructor that modifies the _source_. This is as
odd as it gets in my book.


I agree. IMHO auto_ptr should never be used as a member in a class. No
matter how carefully you document the resulting behavior, when somebody
writes

y = x;

and it changes x, confusion if not disaster is likely to follow.

boost::shared_ptr doesn't have this problem.

Cy


shared_ptr is slower :-)

and unnecessary using move semantics

any class with move semantics can use auto_ptr without problems :-)

Apr 10 '06 #11
Cy Edmunds wrote:
IMHO auto_ptr should never be used as a member in a class. No
matter how carefully you document the resulting behavior, when somebody
writes

y = x;

and it changes x, confusion if not disaster is likely to follow.


Nonsense. BY that argument, raw pointers shouldn't be used in classes,
because after y = x, changing x shouldn't change y.
Of course, that doesn't happen with real classes using raw pointer,
because
they copy the pointed-to object and not the pointer. The same applies
to
auto_ptr members. Your copy ctor will simply copy the pointed-to
object,
and not change the source auto_ptr. You usually can't, because inside
your copy ctor the source auto_ptr is const (assuming X::X(X const&
src)

HTH,
Michiel Salters

Apr 11 '06 #12

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

Similar topics

4
by: Eric Lilja | last post by:
Hello, in my program I have a function (pseudo code): void start_mysql_service() { obtain handle start mysql service using handle if start fails close handle and throw an exception...
3
by: Scott Brady Drummonds | last post by:
Hi, all, I've a fairly small piece of code that is causing me problems. I'm using std::string and am building a string of several dozen characters using several of std::string's functions: a...
21
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...
15
by: Sek | last post by:
Gurus, I am wondering whether it is right to throw an exception from a Property of an object. To get into it further, is it okay to throw exception during 'get' operation? I was searching...
40
by: Sek | last post by:
Is it appropriate to throw exception from a constructor? Thats the only way i could think of to denote the failure of constructor, wherein i am invoking couple of other classes to initialise the...
6
by: Marvin Barley | last post by:
I have a class that throws exceptions in new initializer, and a static array of objects of this type. When something is wrong in initialization, CGI program crashes miserably. Debugging shows...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.