stack/hopr

writing between 0 and 1

Archive for the ‘smart pointer’ tag

Smart Ptr

with 8 comments

It’s a really small smart pointer. 9 lines of code. Of course, I had to cut a few corners (newlines;) to make this happen. But, the readability is maintained.

It doesn’t do much other than being smart. Fit for trivial tasks, such as tracking and deleting local memory allocations, avoiding uninitialized references, etc. It’s so small, it cannot count references. But, it does deallocate when it goes out of scope.

Features:
1. Deallocation when the smart pointer goes out of scope.
2. Invalid reference check.
3. Not dependent on any library (including STL). Useful when you need a small binary footprint.

Restrictions:
1. No reference counting. So, avoid assigning one smart_ptr to another. (Enable test2 in the attached program to see the problem.)
2. Works only with “new” and not with “new []” or “malloc”. Needs further templatization for that to be handled. But, kills the simplicity of the current class.

Code follows:

template<typename T>
class smart_ptr
{
public:
   T* operator->() {if(ptr) return ptr; throw -1;}

   T& operator*() {if(ptr) return *ptr; return NULL;}

   smart_ptr() {ptr = NULL;}

   smart_ptr(T* p):ptr(p) {}

   ~smart_ptr() {if (ptr) delete(ptr); ptr = NULL;}

   smart_ptr& operator=(T* p) {if(ptr) delete(ptr); ptr = p; return *this;}

   bool operator==(const T& p1) {return (p1.ptr == ptr);}

   bool operator==(const int i) {return (i == (int)ptr);}

protected:
   T* ptr;
};

Command line for VC++ compiler to build this program:
1. Open Visual Studio command prompt
2. Compile and Link: >cl smart.cpp
3. Run: >smart.exe

Command line for g++ compiler to build this program:
1. Compile and Link: >g++ smart.cpp -o smart
2. Run: >./smart

For usage, see the complete program: smart.cpp

Written by Amol

October 18th, 2008 at 4:27 pm