Reputation: 10157
My code originally looked something like this:
int SomeObject::operator[]( const string& key ) const
{
return ( *m_Map )[ key ];
}
int SomeObject::operator()( const string& key ) const
{
return ( *m_Map2 )[ key ];
}
Both of these maps had the following signature:
std::map< std::string, int >
And then I read something about STL containers really having no need for explicit heap allocation ( i.e. std::map< ... >* map = new std::map< ... >
), which is what I was doing.
As soon as I change the maps to being stack allocated and remove the pointer dereferences so that it looks like this:
int SomeObject::operator[]( const string& key ) const
{
return m_Map[ key ];
}
int SomeObject::operator()( const string& key ) const
{
return m_Map2[ key ];
}
The compiler complains with the following error ( for both maps ):
Error 1 error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>' (or there is no acceptable conversion)
Wat.
Upvotes: 1
Views: 1427
Reputation: 340516
The problem is that you've marked the functions as const
and operator[]()
on std::map
modifies the map (if the key is not in the map, an element is added with a default value).
You could get away with this when using the pointer because the const
only applied to the member pointer, not to the object the pointer referred to.
Something like the following should get around the const
problem:
int SomeObject::operator[]( const string& key ) const
{
std::map<string,int>::const_iterator it(m_Map.find(key));
if (it == m_Map.end()) {
throw /* something */;
}
return it->second;
}
Upvotes: 5