错误:将“const std::map”传递为“this”参数会丢弃限定符[-fpermissive] [重复]

2023-12-28

从 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
}

发帖前先看一下

这看起来类似于传递 ‘const 此参数会丢弃限定符 [-fpermissive] https://stackoverflow.com/questions/10765787/passing-const-this-argument-discards-qualifiers-fpermissive这是关于Cache, not a std::map。原因是:用户调用了write()方法。该方法未声明const这是有道理的,因为书写可能会修改对象。

但在这里,从映射中获取元素不会修改映射,不是吗?

Question

我的实际用例中的实际地图确实是常量。它在源代码中已完全初始化。修改它没有意义。声明它非常量实际上可以解决问题,但没有意义。


operator[]没有const预选赛在std::map,正如您从文档中看到的,例如std::map::operator[] - cppreference.com http://en.cppreference.com/w/cpp/container/map/operator_at:

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

因此您不能直接在const实例。使用at相反(参考std::map::at - cppreference.com http://en.cppreference.com/w/cpp/container/map/at)如果您能负担得起 C++11 功能。

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

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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

错误:将“const std::map”传递为“this”参数会丢弃限定符[-fpermissive] [重复] 的相关文章

随机推荐