开发者

Overriding new but telling unordered_map not to use it

开发者 https://www.devze.com 2023-01-30 20:34 出处:网络
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

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, b开发者_如何学JAVAut 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消