为什么要重载运算符 new 或运算符删除?
可能的重复:
有什么理由重载全局新建和删除?
在c++中,你可以重载 new/delete 运算符,这样做有什么好处吗?因为在调用operator new之后,其结果值被发送到构造函数,而在调用operator delete之前,析构函数被调用。
Possible Duplicate:
Any reason to overload global new and delete?
In c++ you can overload new/ delete operators, are there any benefits in doing so? Since right after calling operator new
its result value is sent to the constructor and right before calling operator delete
, the destructor is called.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
重载的目的是控制内存分配。在某些情况下,您希望使用自己的分配器而不是标准分配器(例如,当您希望从静态池而不是直接从堆进行分配时)。
The point of overloading is to control the memory allocation. In some cases you want to use your own allocators instead of the standard ones (for example, when you want allocations to be from static pools and not directly from the heap).
如果您想编写自己的分配器,那么它很有用,然后您可以重载
new
和delete
以使该分配器的使用更加自然。It's useful if you want to write your own allocator, then you can overload
new
anddelete
to make the use of that allocator more natural.假设您有移动设备的代码。您可以重载 new 以按照自己的方式管理内存,这可能比默认行为更有效。
Say you have code for a mobile device. You can overload new in order to manage memory your way, maybe more efficiently than the default behavior.
如果您想编写自己的内存使用跟踪器,重载 new 和 delete 可能会很有用。如果您想模拟内存不足的情况也很有用。
Overloading new and delete can be useful if you want to write your own memory usage tracker. Also useful if you want to simulate low memory conditions.