Should C++ programmer avoid memset?

后端 未结 11 1382
遇见更好的自我
遇见更好的自我 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:43

    It is "bad" because you are not implementing your intent.

    Your intent is to set each value in the array to zero and what you have programmed is setting an area of raw memory to zero. Yes, the two things have the same effect but it's clearer to simply write code to zero each element.

    Also, it's likely no more efficient.

    class ArrInit
    {
    public:
        ArrInit();
    private:
        int a[1024];
    };
    
    ArrInit::ArrInit()
    {
        for(int i = 0; i < 1024; ++i) {
            a[i] = 0;
        }
    }
    
    
    int main()
    {
        ArrInit a;
    }
    

    Compiling this with visual c++ 2008 32 bit with optimisations turned on compiles the loop to -

    ; Line 12
        xor eax, eax
        mov ecx, 1024               ; 00000400H
        mov edi, edx
        rep stosd
    

    Which is pretty much exactly what the memset would likely compile to anyway. But if you use memset there is no scope for the compiler to perform further optimisations, whereas by writing your intent it's possible that the compiler could perform further optimisations, for example noticing that each element is later set to something else before it is used so the initialisation can be optimised out, which it likely couldn't do nearly as easily if you had used memset.

提交回复
热议问题