I need to implement a smart pointer in such a way that it does not allow more than 3 references.
my code looks like
template<typename T>
class smartptr{
smartptr():ptr(0), counter(new int){
*counter = 0;
(*counter)++;
};
~smartptr()
{
(*counter)--;
if(*counter == 0)
{
delete counter;
delete ptr;
}
}
T& GetData()
{
return *ptr;
}
T* GetPtr()
{
return ptr;
}
int GetCount()
{
return *counter;
}
smartptr(smartptr<T>& s):ptr(s.ptr), counter(s.counter)
{
if(*counter <= 3)
(*counter)++;
else
{
ptr = nullptr;
counter = new int;
*counter = 0;
}
}
smartptr(T* p) : ptr(p), counter(new int)
{
*counter = 0;
(*counter)++;
}
smartptr& operator=(smartptr &r) // help!!!
{
if(*counter < 3)
{
ptr = r.ptr;
(*counter)++;
}
else if(*counter == 3)
{
ptr = nullptr;
counter = new int;
*counter = 1;
}
else
{
delete ptr;
counter = new int;
*counter = 0;
}
return *this;
}
private:
T* ptr;
int* counter;
};
The problem I'm facing is in the copy assignment. If the reference count drops to 0, the referenced pointer's memory should be released. If the reference count is already 3 when copying, should set it's pointer to nullptr and reference count to 1. Thanks