分类: C/C++
2013-01-22 15:36:15
Item 51: Adhere to convention when writing new and delete
scott这里给了一个new的大致流程伪代码,非常有用:
void * operator new(std::size_t size) throw(std::bad_alloc) { // your operator new might take additional params using namespace std; if (size == 0) { // handle 0-byte requests by treating them as 1-byte requests size = 1; } while (true) { attempt to allocate size bytes; if (the allocation was successful) return (a pointer to the memory); // allocation was unsuccessful; find out what the // current new-handling function is (see below) new_handler globalHandler = set_new_handler(0); set_new_handler(globalHandler); if (globalHandler) (*globalHandler)(); else throw std::bad_alloc(); } }空类或结构都是会占据1字节的,前面的item讲过,调用 set_new_handler,其返回值是当前handler,回调之,如果已经是NULL了,异常之。
E文参考资料是这么说的:get_new_handler 是c++0x新增的
Allocates count bytes from free store. Calls the function pointer returned by std::get_new_handler on failure and repeats allocation attempts until new handler does not return or becomes a null pointer, at which time throws std::bad_alloc.
scott在这个item强调的是new内部的无限循环,和其终止条件;对0内存申请的特殊处理;delete要对空指针进行保护。