c++objectstructobject-lifetime

C++ sharing one variable among more instances of object


Is there any way how can I share one variable (object of class) over more instances of another class? Static member is not what I am looking for. I know that one variable (large object) will be shared among more instances (but not all of them). How can I do that in C++? Thanks for any help.

Example:

class ClassA {
public:
   ...
private:
   ClassB object; // this variable will be shared among more instances of ClassA
}

Solution

  • Well, you'll need to move the member out of the class, and store a pointer instead. You'll also need to count the instances that refer to that independent object. That's a lot of work, but fortunately the C++ standard library has you covered with std::shared_ptr:

    class ClassA {
    public:
       // ...
    private:
       std::shared_ptr<ClassB> object; // this variable will be shared among more instances of ClassA
    };