Hello, i have small problem understanding why my smart pointer class is leaking on self assing. If i do something like this
SmartPtr sp1(new CSine());//CSine is a class that implements IFunction iterface
sp1=sp1;
my colleagues told me that my smart pointer leaks. I added some log messages in my smart pointer to track what is going on and a test and reported this:
SmartPtr sp1(new CSine());
->CSine constructor
->RefCounter increment 0->1
->RefCounter constructor
->SmartPtr constructor
sp1=sp1;
->checks if this.RefCounter == to parameter.RefCounter, if true returns the smart pointer unmodified else modifies the object and returns it with the new values; in this case it returns true and returns the object unchanged.
at the end
->SmartPtr destructor
->RefCounter decrement 1->0
->RefCounter destructor
->CSine destructor
i can't understand why they consider that my smart pointer leaks...any ideas? Thank you in advance!
class SmartPtr
{
private:
RefCounter* refCnt;
void Clear()
{
if(!isNull() && refCnt->Decr() == 0)
delete refCnt;
refCnt = 0;
};
public:
explicit SmartPtr();
explicit SmartPtr(IFunction *pt):refCnt(new RefCounter(pt)){};
SmartPtr(SmartPtr& other)
{
refCnt = other.refCnt;
if (!isNull())
refCnt->Incr();
};
virtual ~SmartPtr(void){Clear();};
SmartPtr& operator=(SmartPtr& other)
{
if(other.refCnt != refCnt)
{
if(!rVar.isNull())
other.refCnt->Incr();
Clear();
refCnt = other.refCnt;
}
return *this;
};
SmartPtr& operator=(IFunction* _p)
{
if(!isNull())
{
Clear();
}
refCnt = new RefCounter(fct);
return *this;
};
IFunction* operator->();
const IFunction* operator->() const;
IFunction& operator*();
const IFunction& operator*() const;
bool isNull() const { return refCnt == 0; };
inline bool operator==(const int _number) const;
inline bool operator!=(const int _number) const;
inline bool operator==(IFunction* _other) const;
inline bool operator!=(IFunction* _other) const;
inline bool operator==(SmartPtr& _other) const;
inline bool operator!=(SmartPtr& _other) const;
};
class RefCounter
{
friend class SmartPtr;
private:
IFunction* p;
unsigned c;
explicit RefCounter(IFunction* _p):c(0),p(_p)
{
if(_p != NULL)
Incr();
cout<<"RefCounter constructor."<<endl;
}
virtual ~RefCounter(void)
{
cout<<"RefCounter destructor."<<endl;
if(c == 0)
delete p;
}
unsigned Incr()
{
++c;
cout<<"RefCounter increment count:"<<c-1<<" to "<<c<<endl;
return c;
}
unsigned Decr()
{
if(c!=0)
{
--c;
cout<<"RefCounter decrement count:"<<c+1<<" to "<<c<<endl;
return c;
}
else
return 0;
}
};