Search code examples
c++new-operatorcalloc

C++: new call that behaves like calloc?


Is there a call I can make to new to have it zero out memory like calloc?


Solution

  • Contrary what some are saying in their answers, it is possible.

    char * c = new char[N]();
    

    Will zero initialize all the characters (in reality, it's called value-initialization. But value-initialization is going to be zero-initialization for all its members of an array of scalar type). If that's what you are after.

    Worth to note that it does also work for (arrays of) class-types without user declared constructor in which case any member of them is value initialized:

    struct T { int a; };
    T *t = new T[1]();
    assert(t[0].a == 0);
    delete[] t;
    

    It's not some extension or something. It worked and behaved the same way in C++98 too. Just there it was called default initialization instead of value initialization. Zero initialization, however, is done in both cases for scalars or arrays of scalar or POD types.