Zero-initializing an array data member in a constructor

后端 未结 5 1225
予麋鹿
予麋鹿 2020-12-17 16:16

I\'ve got an array of class objects, and inside the class object I\'ve got another array that I\'d need to initialize to all zeros. The code compiles and runs, but my outpu

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 16:55

    You are doing it wrong on many levels. The syntax you use does not do what you think it does. What you are doing now is essentially initializing 17th element of the table to 0.

    In your case memset is probably the fastest and simplest. However, it would not work for complex types, so I would consider writing a simple snippet for general case like:

    template
    inline void zero_init(T array[], size_t elements){
     if( std::is_pod() ) memset(array, 0, sizeof(T)*elements);
     else std::fill(begin(array), begin(array)+elements, 0);
    }
    

    This will check if the type is a POD-type, which in this context means it can be initialized via memset and will put 0 for the whole table. If the T does not support it, then for each element an equivalent of element = 0 will be called. Also the check is possible to be evaluated at the compile time, so most probably the if will be compiled away and a simple "one-liner" version will be created for each type at the compilation time.

    You can call it via:

    Cache::Cache()  
    {
      zero_init(byte, 16);
    }
    

提交回复
热议问题