标签:style color 使用 ar 数据 sp div on c
(一)
为什么有人想要替换operator new 和 operator delete呢?三个常见的理由:
(1)用来检测运用上的错误。
(2)为了强化效果。
(3)为了收集使用上的统计数据。
(二)
下面是个快速发展得出的初阶段global
operator new,促进并协助检测“overruns”或“underruns”。
static const int signature = 0xDEADBEEF;
typedef unsigned char Byte;
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();
//将signature写入内存的最前段落和最后段落
*(static_cast<int*>(pMem)) = signature;
*(reinterpret_cast<int*>(static_cast<Byte*>(pMem)+realSize-sizeof(int))) = signature;
return static_cast<Byte*>(pMem) + sizeof(int);
}
这个operator new的主要缺点在于疏忽了身为这个特殊函数所应该具备的“坚持c++规矩”的态度。条款51说所有operator new都应该内含一个循环,反复调用某个new_handling函数,这里却没有。这儿我们暂且忽略之。现在只想专注一个比较微妙的主题:alignment(齐位).
Effective C++ 条款 50:了解new和delete的合理替换时机
标签:style color 使用 ar 数据 sp div on c
原文地址:http://blog.csdn.net/u010470972/article/details/39666635