为特定类覆盖 new 和 delete 运算符的原因是什么?

发布于 2024-12-19 15:11:48 字数 253 浏览 0 评论 0原文

动态内存分配运算符 - new 和 delete 可以针对特定类进行覆盖。我可以定义与 Windows 上 C++ 运行时提供的默认内存分配方案不同的内存分配方案。我有几个与之相关的问题:

  1. 重写特定类的 new 和删除运算符是否可移植,以便它也可以在 unix 上运行?它是 C++ 标准的一部分吗?

  2. 在什么情况下可能需要您重写特定类的内存分配运算符?我能想到的唯一情况是 - 跟踪内存分配是否泄漏。

The dynamic memory allocation operators - new and delete can be overridden for a specific class. I could define a different memory allocation scheme than the default that is provided by the C++ Run-time on windows. I have few questions related to it:

  1. Is overriding new and delete operator for a specific class portable such that it also works on unix? Is it part of the C++ standard?

  2. What are the cases that might require you to override memory allocation operators for a specific class? Only case that I could think of is - tracking memory allocations for leaks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

梦中楼上月下 2024-12-26 15:11:48

如果您需要自动使用不同的内存,例如内存池或共享内存。

还有......许多其他原因: 为什么要替换默认的新并删除运算符?

If you need to automatically use a different memory, for example a memory pool or a shared memory.

And... many other reasons: Why would one replace default new and delete operators?

清风无影 2024-12-26 15:11:48

是的,它是可移植的,但要注意 MS 编译器处理它的“nothrot”部分与 ANSI 标准不同 - 对此很恼火。

至于为什么,是的,跟踪内存、跟踪泄漏、跟踪分配都很好,但这些都可以在全局范围内完成。您可以针对 VRAM 分配之类的内容覆盖 new/delete,但我通常会在不同的函数中看到此类内容。覆盖 new/delete 的最大原因是,您是否可以更好地了解内存系统的使用方式,并且可以比供应商提供的漂亮但通用的 new/delete 更有效地定制您的函数。小对象分配是经常被忽视或实施不善的事情,以及您想要通过分配传递多少信息以用于调试目的。

Yes, it is portable, but beware that MS compilers handle the 'nothrow' part of it different than the ANSI standard - got burned on that.

As to why, yes track memory, tracking leaks, tracking allocations are all nice, but those can be done globally. You could overrride new/delete for something like VRAM allocations, but I usually see that sort of thing called out in different functions. The biggest reason to override new/delete is if you have a better understanding of how your memory system is going to be used, and can tailor your functions more efficiently than the nice, but generic versions of new/delete supplied by your vendor. Small object allocation comes to mind as something that is quite often overlooked or poorly implemented, along with just how much info you want to pass around with allocations for debug purposes.

逆蝶 2024-12-26 15:11:48

如果您想以不寻常的方式对齐收件人。例如,前段时间,

如果您想在预初始化的内存中找到新的类实例,我会使用 8 并使用最后三位来实现其他目标。例如,如果您想从空节点列表中添加新节点到列表中。

If you want to align the addressees in an unusual way. for example some times ago i addressees to 8 and use last three bits for other goals

if you want to locate new class instances in pre-initialized memory. For example if you want to add new node in the list from the list of empty nodes.

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