Original Post
My objects contain the number of references which is 1 when created. The function AddRef increments this number (similar to Microsoft's COM model). I've got a Socket object and a Filter object. The socket object uses the filter and the filter uses the socket object. To explain it a bit: The filter stores a reference to the socket using AddRef(). The Socket::SetFilter() function stores a reference of the filter object. The problem is, objects do only get deleted (= deconstructed) with references=1. But since the filter contains a reference to our socket object, the socket has references=2. So it is not deleted. In case we called "delete sock" directly, it would delete filter (and the socket reference with it) and everything was fine but that's not what it's supposed to be. Is there a solution and, does Microsoft's COM model have one for this problem???
// Simplified code!
#define DELETEOBJECT(obj) { if(obj->references-- == 1) delete obj; obj = 0; }
class Object
{
Object() { references = 1; }
int references;
};
class Filter : public Object
{
Filter(Socket *s) { parent = s->AddRef(); }
~Filter() { DELETEOBJECT(parent); }
Socket *parent;
};
class Socket : public Object
{
~Socket() { DELETEOBJECT(f); }
SOCKET handle; // used for network/Internet stuff
Filter *f;
void SetFilter(Filter *obj)
{
f = obj->AddRef();
}
};
// Simplified main function
int main()
{
Socket *sock = new Socket; // 1 reference
Filter *filter = new Filter; // 1 reference
sock->SetFilter(filter); // filter now has 2 references...
DELETEOBJECT(filter); // ... we don't use the filter in main(), so "delete" it: 1 reference remaining
// do something
// Here comes my problem: Socket has got 2 references
DELETEOBJECT(sock)
}