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