I have a base class in my project in which each newly created instance will store a pointer to itself in a static vector in another class. Unfortunately this creates a circular dependency.
AInstList.cpp
class AInstList {
static std::vector<A*> AList; // List of pointers to instances
static void AddInst(A * newInst) { // Adds pointer to list
...
}
};
A.cpp
class A {
A() {
...
AInstList::AddInst(this);
}
};
Note: This is a highly simplified example. The real version has several children of "A", each with their own instance vectors and unique ids. The vectors are held in an unordered_map using the ids as keys. This makes it easy to sort the object pointers into the correct vector. It allows for adding additional children of "A" without modifying other classes.
The purpose of all this is to be able to easily access or update all instances of a given class without having to look for them. All that is needed is the target class' id.
So...Is there another way of doing this that avoids circular dependencies? Is it worth changing? or should I just deal with the circular dependencies? What is the best way of dealing with it?