0

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?

Camander
  • 147
  • 1
  • 10
  • 1
    what is the actual problem with the circular dependencies? are you having trouble compiling the code or linking it? or is it just a design question. (the latter is basically off topic here.) – Chris Beck Sep 06 '15 at 05:38
  • I have had some trouble with compiling/linking. I figured it out eventually, but I was wondering if there was a good pattern for avoiding them in this situation. There is nothing necessarily wrong with circular dependencies, I just dislike them and feel that they complicate things. I generally tend to avoid them – Camander Sep 06 '15 at 05:48

0 Answers0