author:
- luixiao1223
title: 理解new和delete的合理替换时机
为什么想替换编译器提供的new和delete
- 用来检测运用上的错误.
- 强化效能(默认的new和delete针对的是通用使用情况,设置中庸)如果想追求极致的效率,则需要自己去现实new和delete
- 收集使用上的统计数据
一个例子
static const int signature = 0xDEADBEEF;
typedef unsigned char Byte;
// this code has several flaws — see below
void* operator new(std::size_t size) throw(std::bad_alloc)
{
using namespace std;
size_t realSize = size + 2 * sizeof(int);
void *pMem = malloc(realSize);
if (!pMem) throw bad_alloc();
*(static_cast<int*>(pMem)) = signature;
*(reinterpret_cast<int*>(static_cast<Byte*>(pMem)+realSize-sizeof(int))) = signature;
return static_cast<Byte*>(pMem) + sizeof(int);
}
这个自定义的new有连个缺陷.
- 在失败的情况下没有循环调用new handler.
- 字节对齐的问题可能会让程序崩溃.
使用别人写的库.
- 商业的
- Boost的Pool
总结
- 为了检测运用错误
- 为了收集动态分配内存之使用统计信息
- 为了增加分配和归还的速度
- 为了降低缺省内存管理器带来的空间额外开销.
- 为了弥补缺省分配器中的非最佳齐位.
- 为了将相关独享成簇集中(为了cache的命中率)
- 为了获得非传统的行为.(你可能希望获得共享内存等.)