错误:将“ const std :: map <int,int>”作为“ this”参数传递会丢弃限定符[-fpermissive]

Sté*_*hon 1 c++ dictionary const

从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];
Run Code Online (Sandbox Code Playgroud)

最小的测试用例

// 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
}
Run Code Online (Sandbox Code Playgroud)

发布前先看

这看起来与传递'const相似,此参数将丢弃约a Cache而不是a的限定符[-fpermissive]std::map。原因在于:用户调用write()方法。该方法未声明const,因为编写可能会修改该对象,所以该方法有意义。

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

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

sky*_*ack 5

operator[]正如您在文档中所见,在中没有const限定符std::map,例如std :: map :: operator []-cppreference.com

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

因此,您不能直接在const实例上使用它。如果您负担得起C ++ 11功能,请at改用(ref 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;
Run Code Online (Sandbox Code Playgroud)