Copy an object and make both share a member variable (C++)

Deadly 提交于 2019-12-02 12:07:49

问题


I have been thinking and searching this but I can't solve this question. I would like an object that when copied into another object, both objects share certain member variable. So, when I change the value of the member variable of object1, it's also changes the variable in object2. Example:

class ABC {
public:
    int a = 5;
    //...
}

int main() {
    ABC object1;

    ABC object2 = object1;

    object2.a = 7;      // now, object1.a is equal to 7
    object1.a = 10;     // now, object2.a is equal to 10
}

I know about copy constructors, but I am not sure if it applies here or there is a better method. I have been thinking about using pointers or references, but can't make the trick. Note that I don't want all the objects to share the same variable.


回答1:


What you need is a pointer. The pointer points to the object and then all objects that copy the first one just copy the pointer so that they all point to the same thing. To make life easy we can use a std::shared_ptr to manage the allocation and deallocation for us. Something like:

#include <memory>

class Foo
{
private:
    std::shared_ptr<int> bar;
public:
    Foo() : bar(std::make_shared<int>()) {}
    int& getBar() { return *bar; }
};

int main()
{
    Foo a;
    a.getBar() = 7;
    Foo b = a;
    b.getBar() = 10;
    // now getBar returns 10 for both a and b
    Foo c;
    // a and b are both 10 and c is 0 since it wasn't a copy and is it's own instance
    b = c;
    // now b and c are both 0 and a is still 10
}


来源:https://stackoverflow.com/questions/50917266/copy-an-object-and-make-both-share-a-member-variable-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!