c++ - 在 C++ 中可以将新声明的映射的地址分配给现有映射的地址吗?

标签 c++ pointers dictionary memory-address

假设我有一个类:

class A {
  public:
    int key;
    map<int,int> a;
};

Obj_A1 是 A 类的现有对象。在我的问题中的某个地方,我想构造另一个名为 Obj_A2 的对象并像这样更新 Obj_A2 的成员:

Obj_A2.key = Obj_A1.key + 1;
Obj_A2.a = Obj_A1.a;         // When a is large, this copy operation will be really time consuming.

所以我尝试避开真正的数据传输,考虑到也许我可以将 Obj_A2.a 的地址分配给 Obj_A1.a 的地址。万一Obj_A2.a在内存中就是Obj_A1.a,完全没有数据重复。

所以我做了一些愚蠢的事情(我是 C++ 的新手),即 &Obj_A2.a = &Obj_A1.a,并且有一些编译错误。

有谁知道正确的方法吗?

非常感谢。

最佳答案

听起来你想要一个 shared pointer .

#include <memory>
#include <map>

class A {
  public:
    int key;
    std::shared_ptr<std::map<int,int>> a;
};

int main() {
    A Obj_A1, Obj_A2;
    Obj_A1.key = 0;
    Obj_A1.a = std::make_shared<std::map<int,int>>();

    Obj_A2.key = Obj_A1.key + 1;
    Obj_A2.a = Obj_A1.a;

    // or, more simply
    // Obj_A2 = Obj_A1;
    // Obj_A2.key++;
}

有了这个,Obj_A2.a 将指向与 Obj_A1.a 相同的 map ,另一方将看到对 map 的修改。

关于c++ - 在 C++ 中可以将新声明的映射的地址分配给现有映射的地址吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31106222/

相关文章:

python 3 : Comparing a specific pair of keys and values between two dictionaries

c# - 不可能在字典中返回 IEnumerable 的子类型

c++ - 在消息中显示每个字符的十六进制?

c++ - 使用 ifstream::get 逐字节读取文件

c - 如何在 C 中创建指向二维数组的指针?

c - 调用 free() 时出现段错误

c++ - 防止在 C++ 中构造/初始化数组元素

C++ 双释放或损坏(出): Even with copy constructor and assignment operator

c - 如何让链表的最后一个节点参与冒泡排序?

Python:如何将嵌套列表的字典导出到 Excel