覆盖 new 但告诉 unordered_map 不要使用它

发布于 2024-10-08 05:26:59 字数 541 浏览 0 评论 0原文

我正在为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无人问我粥可暖 2024-10-15 05:26:59

unordered_map 的完整声明,以及所有 STL 容器,包括 allocator 作为最后一个参数:

template<class Key, class Ty, class Hash, class Pred, class Alloc>
    class unordered_map;

这是容器获取其所有内部结构内存的地方。
您可能想在这里实现您自己的分配器。 维基百科看起来是一个很好的起点。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文