Should C++ programmer avoid memset?

后端 未结 11 1421
遇见更好的自我
遇见更好的自我 2020-12-02 20:17

I heard a saying that c++ programmers should avoid memset,

class ArrInit {
    //! int a[1024] = { 0 };
    int a[1024];
public:
    ArrInit() {  memset(a, 0         


        
11条回答
  •  余生分开走
    2020-12-02 20:47

    Zero-initializing should look like this:

    class ArrInit {
        int a[1024];
    public:
        ArrInit(): a() { }
    };
    

    As to using memset, there are a couple of ways to make the usage more robust (as with all such functions): avoid hard-coding the array's size and type:

    memset(a, 0, sizeof(a));
    

    For extra compile-time checks it is also possible to make sure that a indeed is an array (so sizeof(a) would make sense):

    template 
    size_t array_bytes(const T (&)[N])  //accepts only real arrays
    {
        return sizeof(T) * N;
    }
    
    ArrInit() { memset(a, 0, array_bytes(a)); }
    

    But for non-character types, I'd imagine the only value you'd use it to fill with is 0, and zero-initialization should already be available in one way or another.

提交回复
热议问题