Smart pointer in C++

Write a smart pointer (smart_ptr) class.

My initial thoughts(code):

template <class T>
class smart_ptr {
	T * ptr;
	int count;
	public:
	smart_ptr() {
		ptr = new T;
		count = 1;
	}
	
	~smart_ptr() {
		count = count - 1;
		if(count == 0)
			delete ptr;
	}
	
	smart_ptr(const smart_ptr & other) {
		ptr = other.ptr;
		count++;
	}
	
	smart_ptr operator=(const smart_ptr & other) {
		smart_ptr result = new smart_ptr(other);
		return result;
	}
};

Solution:

Smart_ptr is the same as a normal pointer, but it provides safety via automatic memory. It avoids dangling pointers, memory leaks, allocation failures etc. The smart pointer must maintain a single reference count for all instances.

template <class T> class SmartPointer {
public:
	SmartPointer(T * ptr) {
		ref = ptr;
		ref_count = (unsigned*)malloc(sizeof(unsigned));
		*ref_count = 1;
	}
	
	SmartPointer(SmartPointer<T> & sptr) {
		ref = sptr.ref;
		ref_count = sptr.ref_count;
		++*ref_count;
	}
	
	SmartPointer<T> & operator=(SmartPointer<T> & 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 & operator*() {return *ptr;}
	T * operator->() {return ptr;}
protected:	
	T * ref;
	unsigned * ref_count;
};

Comments:
The way that we are using a unsigned pointer to the reference counting is similar as declare it to be static in Java, i.e., all the instances of smart_ptr will share one single copy of the reference counting.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: