Let's say I have two object types, A and B. The relationship between them is many-to-many, but neither of them is the owner of the other.
Both A and B instances need to be aware of the connection; it's not just one way.
So, we can do this:
class A
{
...
private: std::vector<B *> Bs;
}
class B
{
private: std::vector<A *> As;
}
My question is: where do I put the functions to create and destroy the connections?
Should it be A::Attach(B), which then updates A::Bs and B::As vectors?
Or should it be B::Attach(A), which seems equally reasonable.
Neither of those feels right. If I stop working with the code, and come back after a week, I'm sure I won't be able to recall if I should be doing A.Attach(B) or B.Attach(A).
Perhaps it should be a function like this:
CreateConnection(A, B);
But making a global function seems undesirable also, given that it's a function specifically for working with only classes A and B.
Another question: if I run into this problem/requirement often, can I somehow make a general solution for it? Perhaps a TwoWayConnection class that I can derive from or use within classes that share this type of relationship?
What are some good ways to handle this situation... I know how to handle the one-to-many "C owns D" situation quite well, but this one is trickier.
Edit: Just to make it more explicit, this question doesn't involve ownership issues. Both A and B are owned by some other object Z, and Z takes care of all ownership issues. I'm only interested in how to create/remove the many-to-many links between A and B.
PointerandGestureRecognizer. Pointers are owned and managed by the InputManager class. GestureRecognizers are owned by Widget instances, which are in turned owned by a Screen instance which is owned by an App instance. Pointers get assigned to GestureRecognizers so that they can feed raw input data to them, but GestureRecognizers need to be aware of how many pointers there are currently associated with them (to distinguish 1 finger vs. 2 finger gestures, etc.). – Dmitri Shuralyov May 10 '12 at 21:24