나는 스마트 포인터 클래스가 자기 집안에 새어 나가는 이유를 이해하는데 작은 문제가있다. 내가이C++ SmartPointers가 자체 할당에서 유출 되나요?
SmartPtr sp1(new CSine());//CSine is a class that implements IFunction iterface
sp1=sp1;
처럼 뭔가를 할 경우 내 동료 내 스마트 포인터 누출 말해 줬어.
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
그들이 생각하는 이유는 이해할 수없는 내 스마트 포인터 누출 ... 어떤 아이디어 : 나는에 가서 테스트 있는지 추적하기 위해 내 스마트 포인터의 일부 로그 메시지를 추가하고이를보고? 미리 감사드립니다.
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;
}
};
왜 스마트 포인터를 쓰고 있습니까? 수년간의 디버깅을 해왔습니다. Boost의'shared_ptr'은 모든 Boost 구성 요소 중에서 가장 많이 수정 된 클래스 중 하나입니다. 올바르게 진행하는 것은 매우 까다로운 일입니다. – jalf
나는 커튼 뒤에 무슨 일이 일어나고 있는지 어떻게 이해하려고 노력하고있다. –
동료들에게 누출이라고 생각하는 이유를 물어 보았습니까? 그들은 테스트 케이스를 가지고 있습니까? 아니면 애플리케이션에서 누수가 발생했다는보고 만하고 코드가 잘못 될 수는 없다고 비난합니다 .-) –