覆盖 new 但告诉 unordered_map 不要使用它
我正在为 C/C++ 编写一个垃圾收集器作为编程练习,其中一部分涉及全局重写 new
。然而,垃圾收集器还使用一个unordered_map
(来存储指向已分配块的指针),如果映射尝试使用覆盖的new(我认为它会尝试无限循环),事情就会变得严重混乱)。为了创建它,我想使用placement new来避免调用覆盖的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是我定义的结构,但我认为这不相关。)运行时,此代码在unordered_map构造函数内出现段错误。我认为使用新的放置可以解决问题,但显然没有。我很确定 unordered_map 正在内部调用 new 。给它一个分配器(我该怎么做?)可以解决这个问题吗?如果没有,这个问题可以解决吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
unordered_map
的完整声明,以及所有 STL 容器,包括allocator
作为最后一个参数:这是容器获取其所有内部结构内存的地方。
您可能想在这里实现您自己的分配器。 维基百科看起来是一个很好的起点。
The full declaration of
unordered_map
, as well as of all STL containers, includesallocator
as the last parameter: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.