错误:将"const std :: map< int,int>"作为“此"参数传递会丢弃限定符[-fpermissive] [英] error: passing ‘const std::map<int, int>’ as ‘this’ argument discards qualifiers [-fpermissive]
问题描述
从const C ++ std :: map获取条目无法在gcc 5.4.0上编译.
Fetching an entry from a const C++ std::map fails to compile on 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]是关于 Cache
的,而不是 std :: map
的.原因是:用户调用 write()
方法.该方法未声明为 const
,这很有意义,因为编写大概是修改了该对象.
Look before you post
This looks similar to passing ‘const this argument discards qualifiers [-fpermissive] which is about a Cache
, not a std::map
. The cause there: the user calls a write()
method. That method is not declared const
which makes sense since writing presumably modified the object.
但是在这里,从地图中获取元素不会修改地图,是吗?
But here, fetching an element from a map does not modify the map, does it?
我真实用例中的实际地图确实是 const.它已在源代码中完全初始化.修改它没有任何意义.声明为非常量实际上可以解决该问题,但没有任何意义.
The actual map in my real use case is indeed const. It's fully initialized in the source code. It does not make sense to modify it. Declaring it non-const practically solves the problem but does not make sense.
推荐答案
operator []
在 std :: map
中没有 const
限定词代码>,如您从文档中看到的,例如 std :: map :: operator []-cppreference.com :
operator[]
hasn't a const
qualifier in std::map
, as you can see from the documentation, e.g. std::map::operator[] - cppreference.com:
返回对映射到与键等效的键的值的引用,如果该键尚不存在,则执行插入.
因此,您不能直接在 const
实例上使用它.请改用 at
(请参考 std :: map :: at-cppreference.com ),如果您可以负担得起C ++ 11的功能.
Therefore you cannot use it directly on a const
instance. Use at
instead (ref std::map::at - cppreference.com) if you can afford C++11 features.
这些成员函数的声明如下:
Declarations for those member functions follow:
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;
这篇关于错误:将"const std :: map< int,int>"作为“此"参数传递会丢弃限定符[-fpermissive]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!