Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: passing ‘const std::map<int, int>’ as ‘this’ argument discards qualifiers [-fpermissive] [duplicate]

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.

like image 704
Stéphane Gourichon Avatar asked Feb 07 '17 16:02

Stéphane Gourichon


1 Answers

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;
like image 176
skypjack Avatar answered Nov 01 '22 18:11

skypjack