3

From what I know, the const keyword before a function parameter promises that the will not modify the data passed in (if it's passed by ref.) But in this case it seems to me that it blocks the reading of data too. Why is it happening?

I was trying to map some strings to some integers. And there was some function that took the map (by const ref.) and a string (by const ref) as argument. But this somehow doesn't work when I try to do things like: int val = my_map[str];

But when I remove the const keyword from before the map in the parameter, this works just fine. But I don't want to copy the whole map. Why the const is acting weird in this case?

// Of course this is not the actual code. But the error is reproduced.

int get_val(const std::map<std::string, int>& map, const std::string& s) {
    return map[s];  // This doesn't compile
}

int main() {
    std::map <std::string, int> map;
    map["foo"] = 21;
    std::cout << get_val(map, "foo");
}

I expected the output to be 21. But I get this error:

Severity    Code    Description Project File    Line    Suppression State
Error   C2678    binary '[': no operator found which takes a left-hand operand of type 'const std::map<std::string,int,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' (or there is no acceptable conversion)
        with
        [
            _Kty=std::string,
            _Ty=int
        ]   Delete  C:\Users\abusa\source\repos\Delete\Delete\Source.cpp    6
  • 1
    I have linked duplicates that are specific to your problem, i.e., why you cannot use `operator[]` on a `const std::map&`. To get more global understanding, you should look at the purpose of `const`-qualified methods, e.g., via https://stackoverflow.com/questions/3141087/what-is-meant-with-const-at-end-of-function-declaration. – Holt Jun 04 '19 at 08:17
  • it is tempting to use `std::map::operator[]` always, but wheter you want to insert and element or access one, in both cases `operator[]` is doing more than what you actually want, better use `insert` or `find` to insert/find an element in the map and `operator[]` only if you want to "default-construct-value-if-key-not-exists and access" – 463035818_is_not_an_ai Jun 04 '19 at 08:26

0 Answers0