C++ 重载new和delete操作符

原因:

C++标准库提供的new和delete操作符,是一个通用实现,未针对具体对象做具体分析
存在分配器速度慢、小型对象空间浪费严重等问题,不适用于对效率和内存有限制的应用场景
 

好处:

灵活的内存分配控制
提高和改善内存使用效率
检测代码内存错误
获取内存使用统计数据
 

C++标准规定:

分配函数应该是一个类成员函数或全局函数
若分配函数出于非全局命名空间或在全局命名空间声明为静态,则格式错误
要求的内存大小为0 byte时也应返回有效的内存地址
 

备注:

operator new具有一定特殊性,对于自定义类型不重载也可使用,其他操作符则不然
参数个数可以任意,只需保证第一个参数为size_t类型,饭后void *类型即可,其他操作符重载时参数需保持严格一致
因此new操作符更像一个函数重载,而非操作符重载
重载operator new时要兼容默认的operator new错误处理方式
 

实现:

简单实现

 void* operator new(size_t size)
{
if (size < )
return ;
if (size == )
size = ; void *res = malloc(size);
return res;
} void operator delete(void* p)
{
if (p != )
free(p);
} void* operator new[](size_t size)
{
return operator new(size);
} void operator delete[](void* src)
{
operator delete(src);
}

跨平台实现及其内存检测:(来源:http://www.linuxidc.com/Linux/2011-07/39154p4.htm

 #ifndef _DEBUG_NEW_H
#define _DEBUG_NEW_H #include <new> /* Prototypes */
bool check_leaks();
void* operator new(size_t size, const char* file, int line);
void* operator new[](size_t size, const char* file, int line);
#ifndef NO_PLACEMENT_DELETE
void operator delete(void* pointer, const char* file, int line);
void operator delete[](void* pointer, const char* file, int line);
#endif // NO_PLACEMENT_DELETE
void operator delete[](void*); // MSVC 6 requires this declaration /* Macros */
#ifndef DEBUG_NEW_NO_NEW_REDEFINITION
#define new DEBUG_NEW
#define DEBUG_NEW new(__FILE__, __LINE__)
#define debug_new new
#else
#define debug_new new(__FILE__, __LINE__)
#endif // DEBUG_NEW_NO_NEW_REDEFINITION
#ifdef DEBUG_NEW_EMULATE_MALLOC
#include <stdlib.h>
#define malloc(s) ((void*)(debug_new char[s]))
#define free(p) delete[] (char*)(p)
#endif // DEBUG_NEW_EMULATE_MALLOC /* Control flags */
extern bool new_verbose_flag; // default to false: no verbose information
extern bool new_autocheck_flag; // default to true: call check_leaks() on exit #endif // _DEBUG_NEW_H /*
* debug_new.cpp 1.11 2003/07/03
*
* Implementation of debug versions of new and delete to check leakage
*
* By Wu Yongwei
*
*/ #include <new>
#include <stdio.h>
#include <stdlib.h> #ifdef _MSC_VER
#pragma warning(disable: 4073)
#pragma init_seg(lib)
#endif #ifndef DEBUG_NEW_HASHTABLESIZE
#define DEBUG_NEW_HASHTABLESIZE 16384
#endif #ifndef DEBUG_NEW_HASH
#define DEBUG_NEW_HASH(p) (((unsigned)(p) >> 8) % DEBUG_NEW_HASHTABLESIZE)
#endif // The default behaviour now is to copy the file name, because we found
// that the exit leakage check cannot access the address of the file
// name sometimes (in our case, a core dump will occur when trying to
// access the file name in a shared library after a SIGINT).
#ifndef DEBUG_NEW_FILENAME_LEN
#define DEBUG_NEW_FILENAME_LEN 20
#endif
#if DEBUG_NEW_FILENAME_LEN == 0 && !defined(DEBUG_NEW_NO_FILENAME_COPY)
#define DEBUG_NEW_NO_FILENAME_COPY
#endif
#ifndef DEBUG_NEW_NO_FILENAME_COPY
#include <string.h>
#endif struct new_ptr_list_t
{
new_ptr_list_t* next;
#ifdef DEBUG_NEW_NO_FILENAME_COPY
const char* file;
#else
char file[DEBUG_NEW_FILENAME_LEN];
#endif
int line;
size_t size;
}; static new_ptr_list_t* new_ptr_list[DEBUG_NEW_HASHTABLESIZE]; bool new_verbose_flag = false;
bool new_autocheck_flag = true; bool check_leaks()
{
bool fLeaked = false;
for (int i = ; i < DEBUG_NEW_HASHTABLESIZE; ++i)
{
new_ptr_list_t* ptr = new_ptr_list[i];
if (ptr == NULL)
continue;
fLeaked = true;
while (ptr)
{
printf("Leaked object at %p (size %u, %s:%d)/n",
(char*)ptr + sizeof(new_ptr_list_t),
ptr->size,
ptr->file,
ptr->line);
ptr = ptr->next;
}
}
if (fLeaked)
return true;
else
return false;
} void* operator new(size_t size, const char* file, int line)
{
size_t s = size + sizeof(new_ptr_list_t);
new_ptr_list_t* ptr = (new_ptr_list_t*)malloc(s);
if (ptr == NULL)
{
fprintf(stderr, "new: out of memory when allocating %u bytes/n",
size);
abort();
}
void* pointer = (char*)ptr + sizeof(new_ptr_list_t);
size_t hash_index = DEBUG_NEW_HASH(pointer);
ptr->next = new_ptr_list[hash_index];
#ifdef DEBUG_NEW_NO_FILENAME_COPY
ptr->file = file;
#else
strncpy(ptr->file, file, DEBUG_NEW_FILENAME_LEN - );
ptr->file[DEBUG_NEW_FILENAME_LEN - ] = '/0';
#endif
ptr->line = line;
ptr->size = size;
new_ptr_list[hash_index] = ptr;
if (new_verbose_flag)
printf("new: allocated %p (size %u, %s:%d)/n",
pointer, size, file, line);
return pointer;
} void* operator new[](size_t size, const char* file, int line)
{
return operator new(size, file, line);
} void* operator new(size_t size)
{
return operator new(size, "<Unknown>", );
} void* operator new[](size_t size)
{
return operator new(size);
} void* operator new(size_t size, const std::nothrow_t&) throw()
{
return operator new(size);
} void* operator new[](size_t size, const std::nothrow_t&) throw()
{
return operator new[](size);
} void operator delete(void* pointer)
{
if (pointer == NULL)
return;
size_t hash_index = DEBUG_NEW_HASH(pointer);
new_ptr_list_t* ptr = new_ptr_list[hash_index];
new_ptr_list_t* ptr_last = NULL;
while (ptr)
{
if ((char*)ptr + sizeof(new_ptr_list_t) == pointer)
{
if (new_verbose_flag)
printf("delete: freeing %p (size %u)/n", pointer, ptr->size);
if (ptr_last == NULL)
new_ptr_list[hash_index] = ptr->next;
else
ptr_last->next = ptr->next;
free(ptr);
return;
}
ptr_last = ptr;
ptr = ptr->next;
}
fprintf(stderr, "delete: invalid pointer %p/n", pointer);
abort();
} void operator delete[](void* pointer)
{
operator delete(pointer);
} // Some older compilers like Borland C++ Compiler 5.5.1 and Digital Mars
// Compiler 8.29 do not support placement delete operators.
// NO_PLACEMENT_DELETE needs to be defined when using such compilers.
// Also note that in that case memory leakage will occur if an exception
// is thrown in the initialization (constructor) of a dynamically
// created object.
#ifndef NO_PLACEMENT_DELETE
void operator delete(void* pointer, const char* file, int line)
{
if (new_verbose_flag)
printf("info: exception thrown on initializing object at %p (%s:%d)/n",
pointer, file, line);
operator delete(pointer);
} void operator delete[](void* pointer, const char* file, int line)
{
operator delete(pointer, file, line);
} void operator delete(void* pointer, const std::nothrow_t&)
{
operator delete(pointer, "<Unknown>", );
} void operator delete[](void* pointer, const std::nothrow_t&)
{
operator delete(pointer, std::nothrow);
}
#endif // NO_PLACEMENT_DELETE // Proxy class to automatically call check_leaks if new_autocheck_flag is set
class new_check_t
{
public:
new_check_t() {}
~new_check_t()
{
if (new_autocheck_flag)
{
// Check for leakage.
// If any leaks are found, set new_verbose_flag so that any
// delete operations in the destruction of global/static
// objects will display information to compensate for
// possible false leakage reports.
if (check_leaks())
new_verbose_flag = true;
}
}
};
static new_check_t new_check_object;

内存跟踪检测:boost库(来源:http://blog.csdn.net/zmyer/article/details/21475101)

 #include<stdio.h>
#include<map>
#include<boost/thread/mutex.hpp>
#include<boost/thread/locks.hpp>
using namespace boost; #define MEM_CHECK_TABLESIZE 1024*1024
#define MEM_HASH_FUNC(ptr) ((reinterpret_cast<unsigned long>(ptr))%MEM_CHECK_TABLESIZE)
#define MEM_FILENAME_SIZE 1024 boost::mutex mut;
boost::mutex mem_mut;
struct allocMem_ptr_t
{
allocMem_ptr_t()
{
bzero(fileName,sizeof(fileName));
size = ;
line = ;
next = NULL;
}
char fileName[MEM_FILENAME_SIZE];
int size;
int line;
allocMem_ptr_t* next;
}; struct allocMem_ptr_t* allocMem_list[MEM_CHECK_TABLESIZE];
int tableSize = ; struct memLeak_ptr_t
{
memLeak_ptr_t()
{
bzero(fileName,sizeof(fileName));
size = ;
}
char fileName[MEM_FILENAME_SIZE];
int size;
};
std::map<int,memLeak_ptr_t> memLeak_map;
void memCheck()
{
size_t index = ;
mem_mut.lock();
for(int i=;i<MEM_CHECK_TABLESIZE;i++)
{
allocMem_ptr_t* alloc = allocMem_list[i];
if(NULL == alloc) continue;
while(alloc)
{
memLeak_ptr_t memLeak;
sprintf(memLeak.fileName,"%s:%d",alloc->fileName,alloc->line);
memLeak.size = alloc->size;
memLeak_map.insert(std::make_pair(index,memLeak));
alloc = alloc->next;
index++;
}
}
mem_mut.unlock();
std::map<std::string,int> leakCount;
for(int i =;i<memLeak_map.size();i++)
leakCount[memLeak_map[i].fileName] += memLeak_map[i].size;
typedef std::map<std::string,int>::iterator leakCount_iter;
for(leakCount_iter iter = leakCount.begin();iter != leakCount.end();++iter)
{
printf("%s LEAK MEMORY SIZE:%d\n",iter->first.c_str(),iter->second);
}
}
void* operator new(size_t size,const char* file,int line)
{
size_t siz = size + sizeof(allocMem_ptr_t);
allocMem_ptr_t* ptr = (allocMem_ptr_t*)::malloc(siz);
if(NULL == ptr) abort();
void* p = (char*)ptr + sizeof(allocMem_ptr_t);
strncpy(ptr->fileName,file,MEM_FILENAME_SIZE-);
ptr->size = size;
ptr->line = line; mem_mut.lock();
size_t index = MEM_HASH_FUNC(p);
ptr->next = allocMem_list[index];
allocMem_list[index] = ptr;
++tableSize;
mem_mut.unlock();
return p;
} void* operator new[](size_t size,const char* file,int line)
{
return operator new(size,file,line);
} void operator delete(void* ptr)
{
if(NULL == ptr) return;
allocMem_ptr_t* pre = NULL;
size_t index = MEM_HASH_FUNC(ptr);
mem_mut.lock();
allocMem_ptr_t* pointer = allocMem_list[index];
while(pointer)
{
if((char*)pointer + sizeof(allocMem_ptr_t) == ptr)
{
if(NULL == pre)
allocMem_list[index] = pointer->next;
else
pre->next = pointer->next;
--tableSize;
break;
}
pre = pointer;
pointer = pointer->next;
}
mem_mut.unlock();
free(pointer);
} void operator delete[](void* pointer)
{
operator delete(pointer);
} void operator delete(void* pointer,const char* file,int line)
{
operator delete(pointer);
}
void operator delete[](void* pointer,const char* file,int line)
{
operator delete(pointer);
}
上一篇:JDBC中DAO事务函数模版


下一篇:WIN32进阶必备:跟随鼠标移动的子窗口