C ++ - checking all member variables for a condition

A simplified example of my situation:

I have a class with 3 member variables, all integers, e.g.

class Foo
{
   public:
      int A;
      int B;
      int C;
};

I want to have a function that returns a Boolean trueif all the member variables are 0 and falseotherwise.

Easy enough, can be performed using this member function:

bool all_zero()
{
   return (A == 0 && B == 0 && C == 0);
}

I can do this if necessary.

However, in my situation this is not ideal, because:

  • I am not the only person who runs this software.

  • Sometimes new member variables are added to this class (for example, int D).

  • ++, - , . , . .

  • , , all_zero (.. - , && D == 0 , ​​ -).

, ... :

all_zero , - ( int), , ? , , ( -).

, , , all_zero - , , - , all_zero.

+6
1
bool all_zero() const
{
   Foo f{}, g{};
   g = *this;  
   return ::memcmp(&f, &g, sizeof(f));
}

- , , . {} , , .

, ==, , , . . https://isocpp.org/blog/2016/02/a-bit-of-background-for-the-default-comparison-proposal-bjarne-stroustrup.

, ,

bool all_zero(const Foo& f)
{
    Foo g{}, h{};
    h = f;
    return ::memcmp(&g, &h, sizeof(f));
}
+5

All Articles