There are a number of “smart pointer” implementations in C++. Each one has a different set of features and it seems hard to pick one that satisfies scenarios.
auto_ptr: Available as part of the standard C++ library (#include ). Has the several useful features and shortcomings:
- Pointer initializes itself to 0 if not explicitly initialized
- Pointer automatically deletes itself when it goes out of scope
- Only one auto_ptr can point to an object at a given time (so no question of reference counting). If you do x=y auto_ptr x will now point to what was pointed to by y. But y will now point to NULL!!
- Does not work for arrays because it deletes its pointer with delete and not delete []
- Does not work with STL. Warning: May appear to work but reportedly results in subtle devastating bugs
- It is not thread safe
Feature 3 limits its usefulness IMHO. This article – Using auto_ptr Effectively – summarizes auto_ptr features.
shared_ptr: This pointer from the BOOST C++ library uses reference counting. So a shared_ptr that is assigned to another will point at the same object in memory and will increment a reference count to that object. When either of the pointers is deleted the object reference count is decremented. If the object reference count is zero the object is truely deleted from memory.
- Reference counted
- Does NOT do copy on write. If shared_ptr x is assigned to y and later *x (or *y) is changed then the memory location pointed to is changed (just like a regular pointer)
- Cycling references may lead to memory leaks – this is a problem with reference counting itself and not this specific implementation
- Thread safety – some operations seem atomic. See BOOST docs.
- Cannot hold a pointer to an array (see shared_array)
- Pointer automatically deletes itself (or reduces reference count) when it goes out of scope
This may be already added to C++ standard library in the near future (already in?).








