复制一个对象并使两者共享一个成员变量(C ++) [英] Copy an object and make both share a member variable (C++)

查看:100
本文介绍了复制一个对象并使两者共享一个成员变量(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

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

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.

推荐答案

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

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
}

这篇关于复制一个对象并使两者共享一个成员变量(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆