复制一个对象并使两者共享一个成员变量(C++)

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

我一直在思考和搜索这个问题,但我无法解决这个问题。 我想要一个对象,当复制到另一个对象时,两个对象共享某个成员变量。所以,当我更改object1 的成员变量的值时,它也会更改object2 中的变量。示例:

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
}

我知道复制构造函数,但我不确定它是否适用于这里还是有 更好的方法。我一直在考虑使用指针或引用,但无法成功。 请注意,我不希望所有对象共享同一个变量。

你需要的是一个指针。指针指向该对象,然后所有复制第一个对象的对象只复制指针,以便它们都指向同一事物。为了让生活更轻松,我们可以使用 std::shared_ptr 来为我们管理分配和释放。类似于:

#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
}