There is no such thing as a boring project. There are only boring executions.
- Irene Etzkorn
#ifndef SMARTPTR_H
#define SMARTPTR_H
#include <cassert>
using namespace std;
template <typename type>
class smartptr
{
public:
smartptr(type* ptr = 0);
smartptr(const smartptr<type>& orig);
~smartptr();
type* operator->() const;
type& operator*() const;
smartptr<type>& operator=(const smartptr<type>& rhs);
private:
/* The pointer to the object we created */
type* thePointer_;
/* The number of instances pointing to this pointer */
int* count_;
void doDelete();
};
template <typename type>
smartptr<type>::smartptr(type* ptr):thePointer_(ptr), count_(new int)
{
*count_ = 1;
}
template <typename type>
smartptr<type>::smartptr(const smartptr<type>& orig):thePointer_(orig.thePointer_)
{
count_ = orig.count_;
thePointer_ = orig.thePointer_;
++(*count_);
}
template <typename type>
smartptr<type>::~smartptr()
{
doDelete();
}
template <typename type>
type* smartptr<type>::operator->() const
{
return thePointer_;
}
template <typename type>
type& smartptr<type>::operator*() const
{
assert(thePointer_ != 0);
return *thePointer_;
}
template <typename type>
smartptr<type>& smartptr<type>::operator=(const smartptr<type>& rhs)
{
/* check for a=a */
if (this != &rhs)
{
doDelete();
count_ = rhs.count;
}
return *this;
}
template <typename type>
void smartptr<type>::doDelete()
{
assert(*count_ != 0);
*count_ = *count_ - 1;
if (*count_ == 0)
{
delete thePointer_;
delete count_;
}
}
#endif