Search code examples
c++memory-managementmalloccalloc

calloc(), malloc() vs new-ing a struct that has an unordered_map inside


I am creating a struct that has a field that is an unordered_map on the heap. When I use new, I can add to it with no problem. But with calloc, I get an error inserting because the bucket size is 0. It works fine after I call reserve.

So, when calloc is called on the struct, does the unordered_map constructor not run? I am confused why if it was in a struct that was new-ed, it seems to have a non-zero bucket size. And is there a better way to go about this besides calling the reserve? (I can't use delete in this case, so I need to stick with the calloc call)


Solution

  • You are correct, malloc() et al don't run constructors, whereas new does.

    You can't rely on the fact that calling reserve() after calloc() appears to fix the problem. It doesn't. The behaviour of your code is still undefined, and it can blow up at any moment and in any way it pleases.

    One way to fix the problem is to use placement new to call the unordered_map's constructor.

    Alternatively, you could turn the field into a pointer, calloc() the struct, and then use new to allocate and construct the unordered_map. If you do this, you'll have to manually delete it.