通过引用将 std::map 传递给不更新映射的类的构造函数

Passing std::map by reference to constructor of class not updating map

本文关键字:更新 构造函数 映射 引用 std map      更新时间:2023-10-16

>我试图理解为什么在引用 std::map 的类的情况下,它不会更新在类范围之外引用的映射。

这是我的测试程序:

#include <iostream>
#include <map>
class Foo
{
public:
    Foo(int x)
    {
        this->x = x;
    }
    void display()
    {
        cout << x << endl;
    }
protected:
    int x;
};
class FooTest
{
public:
    FooTest(std::map<string, Foo*> & f)
    {
        this->f = f;
    }
    void func()
    {
        f["try"] = new Foo(3);
    }
protected:
    std::map<string, Foo*> f;
};

接下来是做一些基本指令的主要:

int main()
{
    std::map<string, Foo*> f;
    f["ok"] = new Foo(1);
    FooTest test(f);
    test.func();
    for(std::map<string, Foo*>::iterator it = f.begin(); it != f.end(); ++it) {
        it->second->display();
    }
    return 0;
}

这显示了1而我希望有1然后3.我尝试通过将映射引用传递给函数,这效果很好,地图很好地"更新"了。显然,我从构造函数中缺少一些东西,由于某些原因创建了一个新地图,并且不再更新我在 main 函数中给出的地图。

感谢您的帮助!

您可能通过引用传递地图,但数据成员不是引用:

std::map<string, Foo*> f;

所以当你这样做时

this->f = f;

创建输入参数的副本 f 。这个简单的代码说明了这个问题:

void foo(int& i)
{
  int j = i;
  j = 42; // modifies `j`, not i`.
}