Posted by : Sushanth Wednesday 16 December 2015

The misuse of pointers is a major source of bugs: the constant allocation, deallocation and referencing that must be performed by a program written using pointers introduces the risk that memory leaks will occur. Smart pointers try to prevent memory leaks by making the resource deallocation automatic: when the pointer (or the last in a series of pointers) to an object is destroyed, for example because it goes out of scope, the referenced object is destroyed too.

Smart Pointer Implementation:

template
class SmartPointer
{
public:
SmartPointer(T * ptr)
{
    ref = ptr;
    ref_count = (unsigned*)malloc(sizeof(unsigned));
    *ref_count = 1;
}
SmartPointer(SmartPointer & sptr)
{
ref = sptr.ref;
ref_count = sptr.ref_count;
++*ref_count;
}
SmartPointer & operator=(SmartPointer & sptr)
{
    if (this != &sptr)
    {
        ref = sptr.ref;
        ref_count = sptr.ref_count;
        ++*ref_count;
    }
    return *this;
}
~SmartPointer()
{
    --*ref_count;
    if (*ref_count == 0) {
        delete ref;
        free(ref_count);
        ref = NULL;
        ref_count = NULL;
    }
}
T getValue()
{
    return *ref;
}
protected:
    T * ref;
    unsigned * ref_count;
};

How to use smart pointer:

class Widget
{
public:
void Fun();
};
SmartPointer sp(new Widget);
sp->Fun();
(*sp).Fun();

Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Technical Articles - Skyblue - Powered by Blogger - Designed by Johanes Djogan -