mardi 18 juillet 2017

How to share few out of all member variables among set of objects of class?

for ex.. Class A has 5 member variables. Out of 5, I want to share 2 variables among few not all objects of class A.

I can't make them static as I don't want to share them across all the objects of A.

Possible solution according to me:

Class A{
public:
    A(std::shared_ptr a): a_shared(a)

private:
    std::shared_ptr<int> a_shared;
    int b;
}

Class A_factory{
    A* get_A()
    {
        std::shared_ptr a_ptr = a.lock();
        if(!a_ptr) {
            a_ptr = std::make_unique<int>();
            a = a_ptr;
        }
    return A(a_ptr);
    }
    std::weak_ptr<int> a;
    friend class A;
}

Aucun commentaire:

Enregistrer un commentaire