Download demo project - 19 Kb
Download source files - 1.6 Kb
Here is another smart pointer implementation. It's as easy as it gets.
How to use it
#include "/libs/idlsoft/smartptr.h"
using namespace idllib;
SmartPtr<CMyObject> ptr1(new CMyObject);
SmartPtr<CMyObject> ptr2(ptr1);
SmartPtr<CMyObject> ptr3;
ptr3 = new CMyObject;
ptr1 = ptr3;
ptr1->method1();
ptr2 = NULL;
void f(CMyObject *ob);
...
SmartPtr<CMyObject> ptr1(new CMyObject);
f(ptr1);
SmartPtr<CMyObject> f1()
{
return SmartPtr<CMyObject>(new CMyObject);
}
...
SmartPtr<CMyObject> ptr;
ptr = f1();
That's it!
No need to worry about freeing the pointer, the object is deleted
through a standard reference-counting mechanism.
SmartPtr
is the only class you really need here. It can point to anything that was allocated by the new
operator.
How NOT to use it
SmartPtr<CMyObject> ptr;
CMyObject ob;
ptr = &ob;
SmartPtr<CMyObject> ptr1, ptr2;
CMyObject *o2 = new CMyObject;
ptr1 = o2;
ptr2 = o2;
How it is implemented
SmartPtr
holds a pointer to a reference counting object.
Every time we assign a value to SmartPtr
it decrements the reference count
on the current object and increments it for the new one. The reference counter for its
part would delete the allocated object if the reference drops to zero.
The reference counter can be either part of the allocated object (when we implement IRefCount
)
or a separate object (SmartPtr::__RefCounter
) that holds a pointer to it.
See next section for details.
How to optimize memory usage
In order to count references to the allocated object SmartPtr
creates
a special object, which means two memory allocations instead of one.
If you want to optimize the memory usage just implement IRefCount
in your class.
You can do it yourself or use IRefCountImpl
:
class CMyObject : public CObject, public IRefCountImpl<CMyObject> {
...
};
In this case
SmartPtr
will use the built-in counter instead of a
sparate one.