I wrote a simple shared pointer, which I think works pretty well. I would like to see your review of it.
This is the header file:
#pragma once
#include <algorithm>
template <class T>
class SharedPointer
{
private:
T* ptr;
int* counter;
void swapp(SharedPointer& first, SharedPointer& second);
public:
SharedPointer(void);
SharedPointer(T* val);
SharedPointer(const SharedPointer& sp);
T& operator*();
T* operator->();
SharedPointer& operator=(const SharedPointer& sp);
~SharedPointer(void);
};
template <class T>
void SharedPointer<T>::swapp(SharedPointer& first, SharedPointer& second)
{
using std::swap;
swap(first.ptr, second.ptr);
swap(first.counter, second.counter);
}
template <class T>
SharedPointer<T>::SharedPointer(void)
{
ptr = new T;
counter = new int;
*counter = 1;
}
template <class T>
SharedPointer<T>::SharedPointer(T* val) : ptr(val)
{
counter = new int;
*counter = 1;
}
template <class T>
SharedPointer<T>::SharedPointer(const SharedPointer& sp)
{
ptr = sp.ptr;
counter = sp.counter;
++(*counter);
}
template <typename T>
T& SharedPointer<T>::operator*()
{
return *ptr;
}
template <typename T>
T* SharedPointer<T>::operator->()
{
return ptr;
}
template <class T>
SharedPointer<T>& SharedPointer<T>::operator=(const SharedPointer& sp)
{
SharedPointer temp(sp);
swapp(*this,temp);
return *this;
}
template <class T>
SharedPointer<T>::~SharedPointer(void)
{
if(--(*counter) == 0)
{
delete ptr;
delete counter;
}
}
std::shared_ptr
instead." \$\endgroup\$