挂钩新/删除C ++

时间:2015-10-14 17:08:28

标签: c++

我试图在C ++中挂钩new / delete 说到malloc / free,很简单:只需阅读: http://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html

但是,使用new / delete在C ++中进行分配呢?

P.S。我的意思是G ++ / GCC

2 个答案:

答案 0 :(得分:1)

这很简单,只需重载new / new [] / delete / delete []函数:

void* operator new(size_t size)
void* operator new[](size_t size)
void  operator delete(void* ptr)
void  operator delete[](void* ptr)

参见Overloading Global operator new and delete 有关默认新/删除功能的详细信息,请参阅here

答案 1 :(得分:0)

仅全局重载new和delete运算符。我在下面写了一个简单的例子。

void * operator new(size_t size){
    int *p=(int*)malloc(size);
    cout<<*p<<" "<<p<<endl;
    return p;
}
void operator delete(void *p)
{   free(p);
}
void * operator new[](size_t size){
    void *p=malloc(size);
    return p;
}
void operator delete[](void *p){
     free(p);
}