Re: I cannot see the need for auto_ptr?!
From: Karl Heinz Buchegger (kbuchegg_at_gascad.at)
Date: 10/20/03
- Next message: Karl Heinz Buchegger: "Re: I cannot see the need for auto_ptr?!"
- Previous message: Jacob Sparre Andersen: "Re: Spell-checking source code"
- In reply to: grejdanospam_at_pacbell.net: "Re: I cannot see the need for auto_ptr?!"
- Next in thread: Howard Hinnant: "Re: I cannot see the need for auto_ptr?!"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 20 Oct 2003 10:09:42 +0200
grejdanospam@pacbell.net wrote:
>
> >
> > void bar()
> > {
> > std::auto_ptr<LargeObject> p = foo();
> >
> > p->doTheFandango();
> > }
> >
> > where the call to 'foo' transfers ownership up to the local
> > std::auto_ptr in 'bar', which guarantees deallocation even if, as Murphy
> > guarantees will happen, 'doTheFandango' throws an exception.
> >
> >
>
> Yes, but returning a pointer from foo is a bad progamming practice.
Says who?
Sometimes you don't have a choice.
> Why don't you just say that auto_ptr is deprecated ?
You are concentrating too much on returning pointers.
void bar( int Type )
{
Obj* pObj;
pObj = Factory.CreateObject( Type );
// do something
// object no longer needed, delete it.
delete pObj;
}
Now lets say, that the part // do something is rather complicated and there
is a chance that things might go wrong. You insert some tests and do a return.
But when doing so you must not forget do delete the object given to you
from the factory.
void bar( int Type )
{
Obj* pObj;
pObj = Factory.CreateObject( Type );
// do something
...
if( SomeTest ) {
delete pObj;
return;
}
if( SomeOtherTest ) {
...
while( ... ) {
if( AThirdTest )
return;
}
}
// object no longer needed, delete it.
delete pObj;
}
So you see the big? Deep inside the while, there is an if which returns. It happened
to me, that I forgot to delete pObj, because I am human :-)
An auto_ptr saves me from all of this. I don't need to remember to delete pObj, it
is done automatically for me. For the very same reason that you use vector instead
of dynamically allocated arrays, you use an auto_ptr when you must use a pointer, to
free yourself from human errors and to easen maintenance (who says that this test
was there in the first place. It could have been added weeks later).
-- Karl Heinz Buchegger kbuchegg@gascad.at
- Next message: Karl Heinz Buchegger: "Re: I cannot see the need for auto_ptr?!"
- Previous message: Jacob Sparre Andersen: "Re: Spell-checking source code"
- In reply to: grejdanospam_at_pacbell.net: "Re: I cannot see the need for auto_ptr?!"
- Next in thread: Howard Hinnant: "Re: I cannot see the need for auto_ptr?!"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|