Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid mistakes in operator== implementations in C++?

Tags:

c++

operators

I often have classes which provide simple member-by-member comparison:

class ApplicationSettings
{
public:
   bool operator==(const ApplicationSettings& other) const;
   bool operator!=(const ApplicationSettings& other) const;

private:
   SkinType m_ApplicationSkin;
   UpdateCheckInterval m_IntervalForUpdateChecks;
   bool m_bDockSelectionWidget;
   // Add future members to operator==
};

bool ApplicationSettings::operator==(const ApplicationSettings& other) const
{
   if (m_ApplicationSkin != other.m_ApplicationSkin)
   {
      return false;
   }

   if (m_IntervalForUpdateChecks != other.m_IntervalForUpdateChecks)
   {
      return false;
   }

   if (m_bDockSelectionWidget != other.m_bDockSelectionWidget)
   {
      return false;
   }

   return true;
}

bool ApplicationSettings::operator!=(const ApplicationSettings& other) const;
{
   return ( ! operator==(other));
}

Given that C++ at this time does not provide any construct to generate an operator==, is there a better way to ensure future members become part of the comparison, other than the comment I added below the data members?

like image 857
Asperamanca Avatar asked Dec 13 '22 17:12

Asperamanca


1 Answers

It doesn't catch every case, and annoyingly it's compiler and platform dependent, but one way is to static_assert based on the sizeof of the type:

static_assert<sizeof(*this) == <n>, "More members added?");

where <n> is a constexpr.

If new members are introduced then, more often than not, sizeof changes, and you'll induce a compile time failure.

like image 104
Bathsheba Avatar answered Dec 26 '22 00:12

Bathsheba