Mutual dependency of two objects

Quite frequently, I stuble over a situation like this: two objects need to know each other, and we have a mutual aggregation-style dependency (imagine, for example, one object handles a websocket connection, and the other handles a dbus connection, and we need to forward messages in both directions). A UML diagram would look like that:

UML class diagram of mutual aggregation style dependency

A simple way to create this dependency in C++ would be to just pass pointers to each other:

int main() {
  TypeA a;
  TypeB b;

  a.SetB(&b);
  b.SetA(&a);

  // ...
}

I see a potential memory problem here. When main() returns, first b is destroyed, then a. Between those two steps, a might still be running in another thread and access the pointer to b, which is invalid at this time, causing a seg-fault.

My current solution to that problem is using C++11 smart pointers. Both TypeA and TypeB store weak_ptr to the other, and must always check if the pointer is valid before accessing it:

int main() {
  auto a = std::make_shared<TypeA>();
  auto b = std::make_shared<TypeB>();

  a->SetB(b);    // this method converts the shared_ptr to a weak_ptr
  b->SetA(a);    // this method converts the shared_ptr to a weak_ptr

  // ...
}

I am unsure if this really is a proper solution. Also, I’m not so happy that the objects always must be on the heap, an I cannot just place them on the stack anymore.

Can anyone imagine another solution? How to solve this in C++98 or in C?

Source: Windows Questions C++

LEAVE A COMMENT