Auto_ptr is good, use it

I've heard many people say auto_ptr is very error-proven. The main issue is the assign operator, for underlying it's a swap. I believe this is a design mistake too: auo_ptr should have disabled copy constructor and assign operator!

However besides the small issue, auto_ptr do can help avoid memory leaks, look at this code:

bool create_box(RECT rc)
{
   box* pbox=new box(rc);
   if(!pdocument->verify(pbox)) // a creation may not succeed on occasion
   {
      delete pbox; // it's very likely you'll miss this!
      return false;
   }
   pdocument->add(pbox);
   return true;
}

Now let's make the code elegant and robust with auto_ptr:

bool create_box(RECT rc)
{
   auto_ptr<box> pbox(new box(rc));
   if(!pdocument->verify(pbox.get())) // a creation may not succeed on occasion
      return false;
   pdocument->add(pbox.release()); // transfer the ownership from local to the document
   return true;
}

Note this version is also exception-safe.

posted on 2009-09-12 20:53  Tactoth  阅读(120)  评论(0编辑  收藏  举报

导航