drum drum - 3 months ago 15
C++ Question

Map referencing class used by same class

I have a class that needs to keep a list of references of all its objects.
For example:

//A.cpp
class A {
A() {}
someMethod() {}
someOtherMethod() { mapA[0]->someMethod(); }
}

//main.cpp
#include <map>

std::map<int, A*> mapA;
int main(int argc, char const *argv[]) {
int count = 0;
A* a = new A();
mapA[count] = a;
count++;
}


However, because
mapA
is only global to
main.cpp
,
A.cpp
can't reference it. I tried using
extern
, but because the
map
uses the same class
A
, I don't know where to put it.

What's the best way to go about this?

Answer

You might register them in constructor, and make the static var in the class:

// a.hpp
class A {
public:
    A() { as.insert(this); }
    A(const A& rhs) { as.insert(this); }
    ~A() { as.erase(this); }
    static std::set<A*> as; // Declaration
};

// a.cpp
std::set<A*> A::as; // Definition
Comments