【问题标题】:Passing std::map by reference to constructor of class not updating map通过引用类的构造函数而不更新映射来传递 std::map
【发布时间】:2015-01-18 20:00:58
【问题描述】:

我试图理解为什么在引用 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;
};

接下来是执行一些基本指令的 main :

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。 我尝试通过引用将地图传递给函数 func,效果很好,地图很好地“更新”了。显然,我在构造函数中遗漏了一些东西,由于某些原因创建了一个新地图并且不再更新我在主函数中提供的地图。

感谢您的帮助!

【问题讨论】:

  • std::map&lt;string, Foo*&gt; f; 应该是std::map&lt;string, Foo*&gt; &amp; f;

标签: c++ class reference stdmap


【解决方案1】:

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

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

所以当你这样做时

this->f = f;

您复制输入参数f。这个简单的代码说明了这个问题:

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

【讨论】:

  • 是的,我想我明白为什么我弄错了。我相信有一个指向 Foo 的指针就足够了,但是如果我理解的话,当我创建键“try”时,它只会在已复制的地图上创建,对吧?
  • @Hawknight 是的,完全正确。它会影响数据成员f,它不是引用。
  • 我需要使用正确的指针来规避这个问题,对吧?
  • @Hawknight 真的有问题吗?您可以使用引用或指针,具体取决于您希望类的行为方式。请记住,引用不可分配或“可复制”。它们只是引用一个对象。
  • @Hawknight 如果不是我最初认为的拼写错误,请使用指针。最好对仅在函数范围内使用的参数使用引用。
猜你喜欢
  • 1970-01-01
  • 2014-01-29
  • 1970-01-01
  • 2012-03-19
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多