Item 51 new和delete的规则

● 全局new/delete重载

void * operator new(std::size_t size) throw(std::bad_alloc) { using namespace std; if (size == 0) { // C++规定:零申请也要给一个字节 size = 1; } void* mem = NULL; while (true) { mem = malloc(size); if (mem) { return mem; // 退出死循环的条件1:申请成功 } new_handler globalHandler = set_new_handler(0); set_new_handler(globalHandler); if (globalHandler) (*globalHandler)(); // 条件2:让new_handler处理 else throw std::bad_alloc(); // 条件3:异常 } } void operator delete(void* mem) throw() { if (mem == 0) return; // C++规定,对NULL指针delete应该是安全的 free(mem); }

 

● 某个类的new重载

class Base { public: static void * operator new(std::size_t size) throw(std::bad_alloc); static void * operator new[](std::size_t size) throw(std::bad_alloc); static void operator delete(void *mem, std::size_t size) throw(); ... }; void * Base::operator new(std::size_t size) throw(std::bad_alloc) { if (size != sizeof(Base)) // 1. Base是个freestanding类,尺寸永不为零!--C++规定 return ::operator new(size); // 2. 如果是派生类调用,那么交给全局new去处理 ... } void * Base::operator new[](std::size_t size) throw(std::bad_alloc) { return malloc(size); // 3. 只需申请内存,不能处理那些尚不存在的对象,类型也未知 } void Base::operator delete(void *mem, std::size_t size) throw() { if (mem == 0) return; if (size != sizeof(Base)) { // 4. 检查是否来自派生类的调用 ::operator delete(mem); return; } free(mem); } class Derived: public Base // 5. 没有重载new的派生类 {...} // 6. 必须有虚拟的dtor,否则delete调用Base::operator delete时size会传错 Derived *p = new Derived; // 6. 调用 Base::operator new

你可能感兴趣的:(c,null,delete,Class)