Lession learnt when calling a non-const function on a const object. The example below happened whilst refactoring the Icinga 2 Livestatus component code, and it took me a while to figure out its meaning.

/home/michi/coding/icinga/icinga2/components/livestatus/logtable.cpp:365:37: error: passing ‘const icinga::String’ as ‘this’ argument of ‘bool icinga::String::Contains(const string&)’ discards qualifiers [-fpermissive]
  else if (type.Contains("HOST ALERT")) {

‘type’ is a const reference of the Icinga 2 String class.

Dictionary::Ptr LogTable::GetLogEntryAttributes(const String& type, const String& options)
{
...
	if (type.Contains("HOST ALERT")) {

‘Contains’ is a function member of the String class.

bool String::Contains(const String& str)
{
	return boost::algorithm::contains(m_Data, str);
}

By calling the non-const method ‘Contains’ on a const object ‘type’ the compiler requires the method not to modify the object in any way. Therefore the ‘Contains’ function of the String class requires the const qualifier.

bool String::Contains(const String& str) const
{
	return boost::algorithm::contains(m_Data, str);
}
%d bloggers like this: