简体   繁体   English

有没有一种快速的方法可以将 class 的所有 static 成员归零?

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

I have a class with static members that get reset to zero each loop, so something like:我有一个 class 和 static 成员,每个循环都重置为零,所以类似于:

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.使用非静态 class 我可以用零初始化创建一个新的 object 并复制到我想重置的 object 的值。 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.如果可能的话,我只需要记住,对于我在其中创建的每个成员,我还将它添加到“resetStats()”function 中。

Make the the variables non-static members of a class, and use a static instance of that class.使变量成为 class 的非静态成员,并使用该 class 的 static 实例。 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.也就是说,static 变量是全局 state。 Gobal state should be avoided.应该避免使用 Gobal state。

that get reset to zero each loop每个循环都被重置为零

This sounds like ideal use case for non-static storage.这听起来像是非静态存储的理想用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM