规则:如果一个带额外参数的operator new没有“带相同参数”的对应版operator delete,那么就当new的内存分配动作取消并恢复原样时就没有任何operator delete被调用,于是产生内存泄露。
例程:
1 class Wigget{ 2 public:
3 int a; 4 static void* operator new(std::size_t size, std::ostream& logstream) throw(std::bad_alloc){
5 std::cout << "in myself new func !!!" << std::endl; 6 return ::operator new(size);;
7 }
8 static void operator delete(void* pM) throw(){
9 ::operator delete(pM); 10 std::cout << "in delete func !!!" << std::endl; 11 } 12 static void operator delete(void* pM, std::ostream& logstream) throw(){ 13 ::operator delete(pM); 14 std::cout << "in myself delete func !!!" << std::endl; 15 } 16 }; 17
18 int _tmain(int argc, _TCHAR* argv[]){ 19 Wigget *p1 = new(std::cerr) Wigget(); 20 delete p1; 21 return 0; 22 }
运行结果:
由以上代码可以得出以下结论:
- operator delete 是用在当对应的operator new失败的时候(已经分配了内存,但是构造失败),这时编译器需要寻找一个对应的delete函数来收回内存。(出现异常是才会被调用)
- 显式的回收内存调用的还是正常形式的delete.
全局作用域下提供的new:
1 void* operator new(std::size_t) throw(std::bad_alloc); //正常形式的new
2 void* operator new(std::size_t, void *) throw(); //placement形式 new
3 void* operator new(std::size_t, const std::nothrow_t&) throw(); //失败返回NULL的new