I have never used std::shared_ptr before and I don't really know how this smart pointer actually works but I decided to create one to verify my knowledge. Here is my code :
namespace myStd
{
template<class T>
class shared_ptr
{
public :
shared_ptr() : refCount(nullptr), t(nullptr) {}
shared_ptr(T *p) : refCount(new int(1)), t(p) {}
~shared_ptr()
{
this->destroy();
}
shared_ptr(const shared_ptr &p) : refCount(nullptr), t(nullptr)
{
if(p.isvalid())
{
refCount = p.refCount;
t = p.t;
if(isvalid())
(*this->refCount)++;
}
}
void destroy()
{
if(isvalid())
{
--(*refCount);
if((*refCount) <= 0)
{
delete refCount;
delete t;
}
refCount = nullptr;
t = nullptr;
}
}
shared_ptr& operator =(const shared_ptr &p)
{
if(this != &p)
{
if(!p.isvalid())
{
this->destroy();
this->refCount = p.refCount;
this->t = p.t;
if(isvalid())
(*this->refCount)++;
return (*this);
}
if(!isvalid())
{
this->refCount = p.refCount;
this->t = p.t;
if(isvalid())
(*this->refCount)++;
return (*this);
}
else
{
this->destroy();
this->refCount = p.refCount;
this->t = p.t;
if(isvalid())
(*this->refCount)++;
}
}
return (*this);
}
bool isvalid() const {return (t != nullptr && refCount != nullptr);}
int getCount() const {if(refCount != nullptr) return (*refCount); else return 0;}
T* operator ->() {return t;}
T& operator *() {return *t;}
private :
int *refCount;
T *t;
};
}
What am I missing? Did I implement this smart pointer right? Your suggestions would be appreciated.