Search code examples
c++pointersinheritanceshared-ptrstatic-members

Static vector of shared_ptr's for all the objects of a class hierachy


I have a small class hierachy and I want all the objects to have a pointer to any other object from this class hierachy. So I decided a static vector of shared_ptr a good idea. More specifically, I have a class A which has a protected field:

static std::vector< std::shared_ptr<A> > vector_of_objects;

It also has this line in the constructor to fill the vector:

vector_of_objects.emplace_back( this );

Hence the gist of the idea: when creating an object of any class inherited from A, it would call the base class constructor and put a pointer to itself to the static vector.

Frankly, I am puzzled whether this is even possible . Anyway, at this line in contructor I'm getting a linking error - undefined reference to A::vector_of_objects. Do I need to preinitialize the vector somehow?..

In case I'm getting this wrong, is there any way to implement the idea except creating an external vector?


Solution

  • Not sure why you would need such a structure, so far I have the impression that you just need a set (not std::set) of objects. As for the linkage error you should define your static member like this:

    std::vector<std::shared_ptr<A>> A::vector_of_objects;
    

    Otherwise you just have declared it, not defined.

    Updating with a full snippet:

    #include <vector>
    #include <memory>
    
    class A {
        public:
        static std::vector<std::shared_ptr<A>> allObjects;
    
        A() {
            allObjects.emplace_back(this);
        }
    };
    
    std::vector<std::shared_ptr<A>> A::allObjects;