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.