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

╄→гoц情女王★ 提交于 2019-12-02 03:50:21
NathanOliver

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