Friday, February 19, 2016

C++ : auto_ptr

NOTE: auto_ptr is deprecated. Use std::unique_ptr instead !

auto_ptr is a smart pointer facility.
Usually, this is what we do when we manipulate pointers :

void f()
{
   T* pt( new T );
   /*...more code...*/
   delete pt;
}

With auto_ptr, no need to delete the object anymore, it is all  taken care of !

    void f()
    {
      auto_ptr<T> pt( new T );
      /*...more code...*/
    } // cool: pt's destructor is called as it goes out
      // of scope, and the object is deleted automatically

It ensures more robust code as we avoid potential memory leaks.

Ownership


Passing


T* pt1 = new T;
// right now, we own the allocated object
// pass ownership to an auto_ptr
auto_ptr<T> pt2( pt1 );
// use the auto_ptr the same way
// we'd use a simple pointer

*pt2 = 12;       // same as "*pt1 = 12;"

Releasing


...
// use release() to take back ownership
T* pt3 = pt2.release(); // pt3 = pt1 --> points to T object
// delete the object ourselves, since now
// no auto_ptr owns it any more

delete pt3;

Reset


To substitute the pointer owned by auto_ptr with another one, one would use auto_ptr's reset() method:

auto_ptr<T> pt( new T(1) );
pt.reset( new T(2) );
// deletes the first T that was
// allocated with "new T(1)"
 It internally calls delete on T(1) and create a new auto_ptr on T(2).

Notes


  • Never put auto_ptr into standard containers

vector< auto_ptr<T> > v; // No !!!

The problem is that auto_ptr does not quite meet the requirements of a type you can put into containers, because copies of auto_ptrs are not equivalent

Cem SOYDING

Author & Editor

Senior software engineer with 12 years of experience in both embedded systems and C# .NET

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.

 
biz.