【问题标题】:error: passing ‘const std::map<int, int>’ as ‘this’ argument discards qualifiers [-fpermissive] [duplicate]错误:将“const std::map<int, int>”作为“this”参数传递会丢弃限定符 [-fpermissive] [重复]
【发布时间】:2017-02-07 16:57:26
【问题描述】:

从 const C++ std::map 获取条目无法在 gcc 5.4.0 上编译。

test_map.cpp: In function ‘int main()’:
test_map.cpp:9:24: error: passing ‘const std::map<int, int>’ as ‘this’ argument discards qualifiers [-fpermissive]
                 foo[key];

最小测试用例

// Compile with
// g++ test_map.cpp -o test_map

#include <map>

int main() {
    const std::map<int, int> foo;
    foo[0]; // compiles if "const" above is suppressed
}

发帖前先看看

这看起来类似于passing ‘const this argument discards qualifiers [-fpermissive],大约是Cache,而不是std::map。那里的原因:用户调用了write() 方法。该方法没有声明为const,这是有道理的,因为编写可能修改了对象。

但是在这里,从地图中获取元素并不会修改地图,是吗?

问题

我实际用例中的实际映射确实是 const。它在源代码中完全初始化。修改它没有意义。将其声明为非 const 实际上可以解决问题,但没有意义。

【问题讨论】:

  • operator[] 不会从映射中获取任何内容,它会返回对映射中值的可变引用。因此,它不能在const 地图实例中使用。
  • @SamVarshavchik 更重要的是,如果键不存在,它会插入一个值。这就是为什么它不能在 const 映射上使用。
  • 但是在这里,从地图中获取元素并不会修改地图,是吗?您是否尝试过阅读文档?
  • @SamVarshavchik 您的评论是最好的答案。此外,插入元素的访问运算符似乎是诸如 C++ 之类的语言中最愚蠢的事情之一,其中事情的目标是最小化、内存和 cpu-parsimonius,你应该只为你使用的东西付费。甚至 C# 也有这个权利。感谢您指出这一点。
  • 我根本没有发现@StéphaneGourichon 提出了一个愚蠢的问题,我不认为这是重复的:我也不清楚operator[] 不能用于@987654331 @ 地图实例。返回的错误消息也不同于 5+ 个其他“类似”问题:请注意,没有指定 argument

标签: c++ dictionary constants


【解决方案1】:

operator[]std::map 中没有const 限定符,您可以从文档中看到,例如std::map::operator[] - cppreference.com:

返回对映射到与 key 等效的键的值的引用,如果该键不存在则执行插入

因此,您不能直接在 const 实例上使用它。如果您负担得起 C++11 功能,请改用 at(参考 std::map::at - cppreference.com)。

这些成员函数的声明如下:

T& operator[](const key_type& x);
T& operator[](key_type&& x);
T&       at(const key_type& x);
const T& at(const key_type& x) const;

【讨论】:

  • 我忘记在 C++ 映射中,查找不存在的键将键添加到映射。在某些情况下是有道理的,但对我来说并不明显! Ty 现在回答这个问题,我明白我也遇到了这个错误。
猜你喜欢
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多