如何保存指向重新定义的运算符的指针?
我已经重载了 new 和 delete 运算符。我想保存指向“旧”new
和 delete
的指针,以将其调用为“new”new
和 delete
。例如:
#include "h.h"
void * operator new ( size_t size, /*args*/ ) throw (std::bad_alloc)
{
void * p = 0;
p = original_new(size); //calling for 'old' new
//some code
return p;
}
以及类似的操作符delete
。
因此,我尝试在头文件中键入以下内容:
static void * (*original_new)(size_t) = ::operator new;
static void * (*original_new_arr)(size_t) = ::operator new[];
static void (*original_delete)(void *) = ::operator delete;
static void (*original_delete_arr)(void *) = ::operator delete[];
它已成功编译,但我在启动时有核心转储。 在 new
中调用 malloc
是可能的,这确实是一个坏想法。可以调用 new(std::nothrow) 但它也很糟糕。
I have overloaded new and delete operators. I want to save pointers to 'old' new
and delete
to call it into 'new' new
and delete
. For example:
#include "h.h"
void * operator new ( size_t size, /*args*/ ) throw (std::bad_alloc)
{
void * p = 0;
p = original_new(size); //calling for 'old' new
//some code
return p;
}
And the similar operator delete
.
So, I'm trying in my header file to type the following:
static void * (*original_new)(size_t) = ::operator new;
static void * (*original_new_arr)(size_t) = ::operator new[];
static void (*original_delete)(void *) = ::operator delete;
static void (*original_delete_arr)(void *) = ::operator delete[];
It is successfully compiled, but I have core dump on start.
It is possible to call malloc
in new
bad it is really bad idea. It is possible to call new(std::nothrow)
but it is bad too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不需要保存指针;定义一个放置新操作符(任何
operator new
函数需要多个参数)则不会删除现有的操作员;它只会让他们超负荷。要致电
布局运算符新函数中的标准运算符新函数:
请注意,如果布局新返回,您不想执行此操作
除了
::operator new
返回的确切地址之外的任何内容。否则,删除
不起作用。如果您使用任何返回任何内容的新展示位置除了
::operator new
返回的指针之外,您还需要定义一个新的全局
操作符删除
(因为这是将要删除的操作符)称为),这又意味着你必须定义一个新的标准
operator new
也是如此,这样它就可以与您的 new 一起正常工作运算符删除
。为了避免必须实施所有自己管理内存,在你的程序中使用
malloc
和free
实施。
You don't need to save pointers; defining a placement new operator (any
operator new
function which takes more than one argument) doesn'tremove the existing operators; it just overloads them. To call the
standard operator new function from a placement operator new function:
Note that you do not want to do this if your placement new returns
anything but the exact address returned by
::operator new
. Otherwise,delete
won't work. If you use any placement new that return anythingother than a pointer returned by
::operator new
, you need to define anew global
operator delete
(because this is the one that will becalled), which in turn means that you have to define a new standard
operator new
as well, so that it will work correctly with your newoperator delete
. In order to avoid having to implement all of thememory management yourself, use
malloc
andfree
in yourimplementations.