Dissecting Code

Sunday, April 25, 2010

Smart pointers part I : Scoped Pointers

A large amount of problems in C++ are related to memory leaks. Smart pointers allow one to follow the RAII (resource acquisition is initialization) pattern, thereby eliminating leaks that might occur when a class has a naked/dumb pointer in place of a smart pointer. I've taken a stab at implementing a simple scoped_ptr class here, with most of the interface being kept similar to boost.



template <class T>
class scoped_ptr
{
private:
T* m_ptr;
public:
scoped_ptr(T *ptr):m_ptr(ptr){}
~scoped_ptr() {if (m_ptr){ delete m_ptr;} m_ptr=NULL;}
T& operator*()const{return *m_ptr;}
T* operator->() const{return m_ptr;}
T* get() const{return m_ptr};
void reset() {if (m_ptr){ delete m_ptr;} m_ptr=NULL;}
};
Usage:
 
#include <iostream>
#include "scoped_ptr.h"

using namespace std;

class DummyObject
{
private:
int m_i;
public:
int GetI(){return m_i;}
void SetI(int i){m_i = i;}
DummyObject(int i=0): m_i(i){}
};

int main(int argc, char *argv[])
{
scoped_ptr<DummyObject> iptr(new DummyObject());
cout<<iptr->GetI();
iptr->SetI(10);
cout<<iptr->GetI();
return 0;
}

Labels: ,