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.
The problem is that you’ve marked the functions as
constandoperator[]()onstd::mapmodifies 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
constonly applied to the member pointer, not to the object the pointer referred to.Something like the following should get around the
constproblem: