3

I'm writing an assignment and I ran into some issue using the following unordered_map:

std::unordered_map<std::string, Account*> m_accounts_map;

Compiles without errors:

const Account& Bank::getBankAccount(const std::string ID) const
{
    return *m_accounts_map.at(ID);
}

Does not compiles:

const Account& Bank::getBankAccount(const std::string ID) const
{
    return *m_accounts_map[ID];
}

The above code generate the following compilation error:

error: passing 'const std::unordered_map, Account*>' as 'this' argument discards qualifiers [-fpermissive]

But when I remove the const it compiles:

const Account& Bank::getBankAccount(const std::string ID)
{
    return *m_accounts_map[ID];
}

According to std::unordered_map::operator[] the difference is:

A similar member function, unordered_map::at, has the same behavior when an element with the key exists, but throws an exception when it does not.

But that's does not explain this behavior. I don't understand why dose operator[] discards qualifiers.

So what is the subtle differences I'm not aware of?

Matan
  • 43
  • 6

0 Answers0