Introduction
Sometimes it is necessary to use something automatic instead of classical C++ pointers. For example you want that your pointer is automatically deleted. For this we need a class that automatize this things. Such class is called Smart Pointer.
template<class T><BR>class SmartPointer<BR>{<BR>public:<BR> SmartPointer(T* pointer)<BR> : mPointer(pointer)<BR> {}<BR> ~SmartPointer()<BR> {<BR> delete mPointer;<BR> release();<BR> }<BR> T* get()<BR> {<BR> return mPointer;<BR> }<BR> void release()<BR> {<BR> mPointer = NULL;<BR> }<BR> bool valid() const<BR> {<BR> return mPointer != NULL;<BR> }<BR> T* operator-> ()<BR> {<BR> return mPointer;<BR> }<BR> T& operator* ()<BR> {<BR> return *mPointer;<BR> }<BR>private:<BR> T* mPointer;<BR> SmartPointer(SmartPointer&) {}<BR> SmartPointer& operator= (SmartPointer&) {}<BR>};
We need a template class, because it should work with each type. The function get() returns the pointer, with the function valid() you can check whether the pointer has a valid value or not and the function release() sets the value of the pointer to NULL. We overload two operators: -> for the pointer and * for the value of the pointer. The most important thing of the smart pointer is this:
~SmartPointer()
{
delete mPointer;
release();
}
In the desctructor we automatically delete the pointer and then we set the value of the pointer to NULL.
This is an example how to use the smart pointer:
int main(int, char**)
{
SmartPointer<int> pointer(new int);
*pointer = 14;
return 0;
}
It is very simple. I hope my article helped you.