Overriding new but telling unordered_map not to use it
-
11-10-2019 - |
Question
I'm writing a garbage collector for C/C++ as a programming exercise, and part of this involves globally overriding new
. However, the garbage collector also uses an unordered_map
(to store pointers to allocated blocks), and things will get seriously messed up if the map tries to use the overridden new (it will try to infinitely loop I think). To create it, I wanted to use placement new to avoid calling the overridden new:
void *buffer = malloc(sizeof(unordered_map<void *, mem_t *>));
unordered_map<void *, mem_t *> map = new(buffer) unordered_map<void *, mem_t *>();
(mem_t is a struct I've defined, but I don't think that's relevant.) When run, this code segfaults inside the unordered_map constructor. I thought using placement new would have fixed the problem, but apparently not. I am pretty sure that unordered_map is calling new internally. Will giving it an allocator (how do I do that?) fix this problem? If not, is this problem fixable?
Solution
The full declaration of unordered_map
, as well as of all STL containers, includes allocator
as the last parameter:
template<class Key, class Ty, class Hash, class Pred, class Alloc>
class unordered_map;
That's where a container gets memory for all its internal structures. You probably want to implement your own allocator here. Wikipedia looks like a good starting point.