auto_ptr's exception safe

K

Kuba_O

Hello, i've got simple question about std::auto_ptr: what makes it is
exceptions safe?
Lets say i have class "int_smart_ptr" implemented like this:

class int_smart_ptr
{
private:
int *int_obj;
public:
explicit int_smart_ptr(int *_p)throw():int_obj(_p){}
~int_smart_ptr()throw(){delete int_obj;}
};

Is this class exception safe? When exception occur in scope in
int_smart_ptr was use, would destructor be call?
If yes, why?
If not, what feature of std::auto_ptr decide it is safe in case of
exception?

I hope someone understand my english :D

Regards
Kuba
 
M

Michiel.Salters

Kuba_O said:
Hello, i've got simple question about std::auto_ptr: what makes it is
exceptions safe?

Simple: a proper copy ctor, assignment and destructor.
Lets say i have class "int_smart_ptr" implemented like this:

class int_smart_ptr
{
private:
int *int_obj;
public:
explicit int_smart_ptr(int *_p)throw():int_obj(_p){}
~int_smart_ptr()throw(){delete int_obj;}
};

Is this class exception safe?

No. If you copy one, and an exception is thrown, both the original and
the copy will be destroyed. Both destructors will attempt to delete the
same int*, leading to a double-deletion bug.
When exception occur in scope in int_smart_ptr was use, would
destructor be call? If yes, why?

Yes, because destructors are always called for all objects from the
scope being exited. Of course, auto_ptr has a copy ctor and an
operator= defined which avoid the double-deletion bug you have.

HTH,
Michiel Salters
 
K

Kuba_O

25.01.2006, (e-mail address removed):
No. If you copy one, and an exception is thrown, both the original and
the copy will be destroyed. Both destructors will attempt to delete the
same int*, leading to a double-deletion bug.
I know that, it was just simple sample ;)
Yes, because destructors are always called for all objects from the
scope being exited.
I did not know that, now everything is clear.
Thanks for inform me about such essential behavior of exceptions :D
Of course, auto_ptr has a copy ctor and an
operator= defined which avoid the double-deletion bug you have.
Yeap.

out.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top