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

时间:2017-02-07 16:57:26

标签: 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];

最小测试用例

// 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实际上解决了这个问题,但是没有意义。

1 个答案:

答案 0 :(得分:4)

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

  

返回对映射到等效于键的键的值的引用,如果此类键尚不存在则执行插入

因此,您无法直接在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;