mathieu wrote:
Quote:
class Object
{
public:
Object():ReferenceCount(0) {}
virtual ~Object() { assert(ReferenceCount == 0); }
>
void Register() {
ReferenceCount++;
}
void UnRegister() {
ReferenceCount--;
if(!ReferenceCount) delete this;
}
private:
long ReferenceCount;
};
>
class Foo : public Object
{
public:
int F;
};
|
You have a basic problem with your reference-counting base class there.
Assume you have one instance of Foo allocated behind one SmartPointer
(let's name it fooPtr1). The reference count of that Foo instance will be 1.
Also assume you have another instance of Foo allocated and shared
between two SmartPointers (let's name them fooPtr2 and fooPtr3). The
reference count of this instance will be 2.
Now assume you do a "*fooPtr1 = *fooPtr2;", which is not in any way a
far-fetched thing to do. What happens?
What happens is that now the object behind fooPtr1 will have its
reference counter set to 2, even though only one smart pointer is
pointing to it. When fooPtr1 is destroyed, it will decrement that
counter to 1, not destroy the object, and you have a memory leak.
Assume the inverse situation: "*fooPtr2 = *fooPtr1;" What happens?
What happens is that now the second object will have its reference
counter set to 1 even though two smart pointers are pointing to it. When
one of then is destroyed, the other will point to freed memory. Kaboom.
The solution to this problem is rather simple, though.