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
}
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?
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[]
hasn't a const
qualifier in std::map
, as you can see from the documentation, e.g. std::map::operator[] - cppreference.com:
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With