May 20, 2010

C++ auto_ptr and shared_ptr


Good article on why and how to use it Another good article on when and how to use it
  auto_ptr<T> ptr( new T );
} // when ptr goes out of scope it deletes the underlying object!
  • auto_ptr employs the "exclusive ownership" model. This means that you can't bind more than one auto_ptr object to the same resource.
  • Be careful when passing as a parameter to a method by value because on returning the pointer will point to nothing. The copy in the method will destroy the pointer when the method ends, so pass it by reference.
  • Also because of this do not use it with template libraries!


  • Unlike auto_ptr, shared_ptr uses reference counting so multiple "shared_ptr"s can point to the same resource.
  • Destructor decrement the reference count. When it reaches zero the resource is "delete"d.
  • Can have a user defined deleter, so shared_ptr need not necessarily hold a "pointer to something" type resource, it could be a file handle, etc. Define a "delete" function to delete the custom resource
  • Be careful of cyclic references, the objects will not be able to delete one another

No comments: