如何称呼原来的“operator new”?如果我超载了呢?
假设我需要重载全局 ::operator new()
用于为每个分配的对象存储额外的数据。所以基本上它会这样工作:
- 对于每次调用全局
::operator new()
,它将获取传递的对象大小并添加额外数据的大小, - 它将分配一个内存块< /em> 的大小在上一步中推导出来,
- 它将把指针偏移到块中未被额外数据占用的部分,并将该偏移值返回给调用者
::operator delete()
将执行相同的操作相反 - 移动指针、访问额外数据、释放内存。
现在的问题是如何分配内存?当然,我可以调用 malloc()
或一些特定于平台的函数(通常是这样做的)。但通常当我需要在 C++ 中分配原始内存时,我会调用 ::operator new()
。我可以调用原始的 ::operator new()
从重载的全局 ::operator new()
内部进行内存分配吗?
Suppose I need to overload global ::operator new()
for storing extra data with each allocated object. So basically it would work this way:
- for each call to global
::operator new()
it will take the object size passed and add the size of extra data - it will allocate a memory block of size deduced at previous step
- it will offset the pointer to the part of the block not occupied with extra data and return that offset value to the caller
::operator delete()
will do the same in reverse - shift the pointer, access extra data, deallocate memory.
Now the question is how do I allocate memory? Of course I can call malloc()
or some platform-specific function (that's how it is usually done). But normally when I need to allocate raw memory in C++ I call ::operator new()
. Can I call the original ::operator new()
to do the memory allocation from inside my overloaded global ::operator new()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法访问它们,因为它并不是真正的超载,而是替换。当您定义自己的
::operator new
时,旧的就会消失。差不多就是这样了。本质上,您需要从自定义
::operator new
调用malloc
。不仅如此,还要按照18.4.1.1/4中的指示正确处理错误:You can't access them because it isn't really overloading, it's replacement. When you define your own
::operator new
, the old one goes away. That's pretty much that.Essentially, you need to call
malloc
from a custom::operator new
. Not only that, but also follow the directions in 18.4.1.1/4 to properly handle errors: