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];
Minimal test case
// 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
}
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?
Question
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.