try, finally

Noel Yap noel.yap@gmail.com
Thu Mar 20 13:30:00 GMT 2008


On Wed, Mar 19, 2008 at 12:09 PM, me22 <me22.ca@gmail.com> wrote:
> On Wed, Mar 19, 2008 at 3:02 PM, Jason Cipriani
>
> <jason.cipriani@gmail.com> wrote:
>
> >  Does std or boost have some kind of "smart pointers" that let me
>  >  define the cleanup actions without having to write too much additional
>  >  code?
>  >
>
>  Yup, boost::shared_ptr (std::shared_ptr, in C++1x) will let you do that.
>
>  boost::shared_ptr<xmlDoc> doc( xmlReadFile(...), xmlFreeDoc );
>  if (!doc) throw something();

If the pointers never leave the scope, I would use boost::scoped_ptr.
Since shared_ptr keeps a reference count, locks (or atomic operations)
need to be used in order to make it thread safe.

Use shared_ptr iff the ownership needs to be shared.  Use auto_ptr iff
the ownership needs to be transferred and the pointer must never be
copied.  Use scoped_ptr iff the life span of the memory ought to end
when the local scope ends.

Noel



More information about the Gcc-help mailing list