Zero-initializing an array data member in a constructor

后端 未结 5 1224
予麋鹿
予麋鹿 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:48

    In Cache constructor, when you do :

    byte[16]={0};
    

    You are only setting the 16th byte of your array (which is out of bounds, so this operation has undefined behavior). Array objects are default-initialized in C++, because you store int, no initialization is performed.

    You can use std::fill to initialize it :

    Cache::Cache()  
    {
      std::fill(byte, byte+16, 0);
    }
    

    Or you can use a regular for-loop over your array.

提交回复
热议问题