问题描述
假设我需要重载全局 ::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:
- 对于每次调用全局
::operator new()
它将获取传递的对象大小并添加额外数据的大小 - 它将分配一个内存块,其大小在上一步推导出
- 它会将指针偏移到没有被额外数据占用的块部分,并将该偏移值返回给调用者
- 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()
将反向执行相同的操作 - 移动指针、访问额外数据、释放内存.
::operator delete()
will do the same in reverse - shift the pointer, access extra data, deallocate memory.
现在的问题是如何分配内存?当然,我可以调用 malloc()
或一些特定于平台的函数(通常就是这样完成的).但通常当我需要在 C++ 中分配原始内存时,我会调用 ::operator new()
.我可以调用原始的 ::operator new()
来从重载的全局 ::operator new()
内部进行内存分配吗?
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()
?
推荐答案
您无法访问它们,因为它不是真正重载,而是替换.当您定义自己的 ::operator new
时,旧的就会消失.差不多就是这样.
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.
本质上,您需要从自定义 ::operator new
调用 malloc
.不仅如此,还要按照18.4.1.1/4中的指示正确处理错误:
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:
默认行为:
——执行一个循环:在循环内,函数首先尝试分配请求的贮存.尝试是否涉及对标准 C 库的调用函数 malloc 未指定.
— Executes a loop:Within the loop, the function firstattempts to allocate the requestedstorage. Whether the attempt involvesa call to the Standard C libraryfunction malloc is unspecified.
—返回一个指向分配的指针如果尝试成功,则存储.否则,如果最后一个参数为set_new_handler() 是一个空指针,抛出 bad_alloc.
—Returns a pointer to the allocatedstorage if the attempt is successful.Otherwise, if the last argument toset_new_handler() was a null pointer,throw bad_alloc.
——否则,函数调用当前的 new_handler(18.4.2.2).如果被调用的函数返回,循环重复.
— Otherwise, thefunction calls the current new_handler(18.4.2.2). If the called functionreturns, the loop repeats.
——循环尝试分配时终止请求的存储成功或当调用 new_handler 函数时不返回.
— The loopterminates when an attempt to allocatethe requested storage is successful orwhen a called new_handler functiondoes not return.
这篇关于我如何称呼原始的“运营商新"?如果我超载了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!