Error: passing const xxx because this argument xxx discards qualifiers

I have a problem with porting my functor from windows to linux. (functor to go to stl :: map for strictly weak ordering) The original looks like this:

struct stringCompare{ // Utilized as a functor for stl::map parameter for strings bool operator() (string lhs, string rhs){ // Returns true if lhs < rhs if(_stricmp(lhs.c_str(), rhs.c_str()) < 0) return true; else return false; } }; 

Since linux does not support _stricmp, but uses strcasecmp instead, I changed it to:

 struct stringCompare{ bool operator() (string lhs, string rhs){ // Returns true if lhs < rhs if(strcasecmp(lhs.c_str(), rhs.c_str()) < 0) return true; else return false; } }; 

And now he complains about the "const" parameters:

 passing const stringCompare as this argument of bool stringCompare::operator() (std::string, std::string)Γ’ discards qualifiers 

I'm not quite sure why it assumes stringCompare should be constant ...

And the line in which he is crazy about this is created:

 if(masterList->artistMap.count(songArtist) == 0) 

artistMap is a stl :: map with a string key.

I am not sure where I am going wrong. I tried changing the parameters of the bool operator () to const, as it seems to be complaining about some parameter mismatch. This did not work and did not change 'bool operator ()' to 'const bool operator ()'.

As far as I know, strcasecmp is a const function, so you should consider whether I pass it constant or constant parameters (c_str () is also a constant), so I'm not quite sure where I am going wrong.

I have similar problems in googled, but I still can not understand the meaning of this problem from what I saw both in stackoverflow and in several other places.

The data type in which I use this is:

 map<string, set<song, setSongCompare>*,stringCompare > artistMap; 
+6
source share
1 answer

Two things:

  • Define bool operator() as const . This is just good practice. This tells the compiler that this function will not have side effects for class member variables.

  • Add const & qualifiers to the lhs and rhs arguments. It’s good practice to pass permalinks instead of copying all the memory. By declaring links as const , you tell the compiler that this function should not have side effects for reference objects.

Your operator() should look like this:

 bool operator() (const string &lhs, const string &rhs) const { return strcasecmp(lhs.c_str(), rhs.c_str()) < 0; } 
+10
source

Source: https://habr.com/ru/post/911141/


All Articles