Search code examples
c++cconstructordynamic-memory-allocationstdvector

Mimicking C calloc array behavior in C++


There is some code that exists in C which uses calloc() to create what effectively is a vector. It looks like this:

uint64_t *reverseOrder = (uint64_t *)calloc((size + 1), sizeof(uint64_t));

I want to mimic this behavior with C++ syntax and vectors so that it works the same de-facto. Can I use the following syntax?

std::vector<uint64_t> reverseOrder(size + 1, 0);

I know that calloc() actually goes through the memory and sets them to 0, so I'm wondering if this is the case.


Solution

  • You can just write

    #include <vector>
    #include <cstdint>
    
    //...
    
    std::vector<uint64_t> reverseOrder( size + 1 );
    

    and all elements of the vector will be zero-initialized.