简体   繁体   中英

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?

A static data-member must not only be declared in the class-definition, but also defined in exactly one translation-unit, if ODR used.

As a side-note, your static vector should only store weak_ptr s, unless you really want to keep them all alive like forever (in which case raw pointers would be sufficient anyway).

Also, take a look at std::enable_shared_from_this for your base-class, if they really all shall be shared_ptr -managed.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM