Connecting Tech Pros Worldwide Forums | Help | Site Map

auto_ptr's exception safe

Kuba_O
Guest
 
Posts: n/a
#1: Jan 25 '06
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
--

empty


Michiel.Salters@tomtom.com
Guest
 
Posts: n/a
#2: Jan 25 '06

re: auto_ptr's exception safe



Kuba_O wrote:[color=blue]
> Hello, i've got simple question about std::auto_ptr: what makes it is
> exceptions safe?[/color]

Simple: a proper copy ctor, assignment and destructor.
[color=blue]
> 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?[/color]

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.
[color=blue]
> When exception occur in scope in int_smart_ptr was use, would
> destructor be call? If yes, why?[/color]

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

Kuba_O
Guest
 
Posts: n/a
#3: Jan 25 '06

re: auto_ptr's exception safe


25.01.2006, Michiel.Salters@tomtom.com:[color=blue][color=green]
> > Is this class exception safe?[/color]
>
> 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.[/color]
I know that, it was just simple sample ;)
[color=blue]
> Yes, because destructors are always called for all objects from the
> scope being exited.[/color]
I did not know that, now everything is clear.
Thanks for inform me about such essential behavior of exceptions :D[color=blue]
> Of course, auto_ptr has a copy ctor and an
> operator= defined which avoid the double-deletion bug you have.[/color]
Yeap.

out.
--

empty

Closed Thread


Similar C / C++ bytes