template<class T>
class boost::shared_ptr< T >
A smart pointer class: multiple shared_ptr's refer to one object.
This class keeps a reference counter to see how many shared_ptr's refer to the object. When a shared_ptr is deleted, the reference counter is decremented and if the object is longer referenced, it is deleted.
- Advantages: (it's easy)
-
Automatic tracking of memory allocations. No memory leaks.
-
Syntax hardly changes (you still use * and ->)
- Disadvantages: (you have to be careful)
-
If the object which a shared_ptr refers to gets modified, it affects all shared_ptrs sharing the object.
-
Constructing 2 shared_ptr's from the same ordinary pointer gives trouble.
- Example:
{
shared_ptr<int> i_ptr1(new int (2));
shared_ptr<int> i_ptr2(i_ptr1);
unique_ptr<int> a_ptr(new int(3));
shared_ptr<int> i_ptr3(a_ptr);
{
int * i_ptr = new int (2);
i_ptr1.reset(i_ptr);
}
}
{
int * i_ptr = new int (2);
shared_ptr<int> i_ptr1 (i_ptr);
shared_ptr<int> i_ptr2 (i_ptr);
}