Is there a quick way to zero all the static members of a class?

Viewed 50

I have a class with static members that get reset to zero each loop, so something like:

class Stats
{
   static inline int counter1, counter2;
   static inline float time;
   static void resetStats() 
   {
       counter1 = 0;
       counter2 = 0;
       time = 0.f;
   }
}

With a non-static class I can create a new object of it with zero-initialization and copy to the object I want to reset the values of. If it's possible I just have to remember that for each member I create in it I also add it to the "resetStats()" function.

1 Answers

Make the the variables non-static members of a class, and use a static instance of that class. This way you can use value initialisation to set all members to zero:

class Stats
{
    static inline struct {
        int counter1, counter2;
        float time;
    } data;

    static void resetStats() 
    {
        data = {};
    }

That said, static variables are global state. Gobal state should be avoided.

that get reset to zero each loop

This sounds like ideal use case for non-static storage.

Related