Question

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)

Was it helpful?

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.

OTHER TIPS

C memory allocation functions don't usually call constructors. See malloc vs new. The first answer sums it up quite nicely: don't use malloc in C++.

calloc does nothing to initialize your objects qua objects. It's basically handing you a pointer to some memory filled with zeroes. So any internal fields that require initialization, like your map, don't get it. You shouldn't be using calloc in conjunction with objects. (Indeed, you probably shouldn't need it at all.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top