Take the 2-minute tour ×

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)

share|improve this question
Why are you forced to use calloc? –  Pubby Apr 11 '13 at 7:46
it's legacy code. I'm just adding a new field to it which happens to be an unordered map. –  jamesatha Apr 11 '13 at 7:47
Fair enough. I suppose that means you can't use placement new either? –  Pubby Apr 11 '13 at 7:49
add comment

3 Answers

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.

share|improve this answer
add comment

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++.

share|improve this answer
Usually? They'll never call the constructor. (well, char may be the one exception) –  Pubby Apr 11 '13 at 7:48
Seeing as I cannot possibly know the behaviour of every implementation, I stuck with usually. –  Martin Törnwall Apr 11 '13 at 7:50
add comment

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.)

share|improve this answer
add comment

Your Answer


