首页 > 代码库 > Item 51:写new和delete时请遵循惯例
Item 51:写new和delete时请遵循惯例
外部operator new
void * operator new(std::size_t size) throw(std::bad_alloc){
if(size == 0) size = 1;
while(true){
// 尝试申请
void *p = malloc(size);
// 申请成功
if(p) return p;
// 申请失败,获得new handler
new_handler h = set_new_handler(0);
set_new_handler(h);
if(h) (*h)();
else throw bad_alloc();
}
}
成员operator new
class Base{
public:
static void* operator new(std::size_t size) throw(std::bad_alloc);
};
class Derived: public Base{...};
Derived *p = new Derived; // 调用了 Base::operator new !
能够在Base::operator new
中推断參数size
。当大小不为sizeof(Base)
时调用全局的new
:
void *Base::operator new(std::size_t size) throw(std::bad_alloc){
if(size != sizeof(Base)) return ::operator new(size);
...
}
由于:
外部operator delete
void operator delete(void *rawMem) throw(){
if(rawMem == 0) return;
// 释放内存
}
成员operator delete
class Base{
public:
static void * operator new(std::size_t size) throw(std::bad_alloc);
static void operator delete(void *rawMem, std::size_t size) throw();
};
void Base::operator delete(void *rawMem, std::size_t size) throw(){
if(rawMem == 0) return; // 检查空指针
if(size != sizeof(Base)){
::operator delete(rawMem);
}
// 释放内存
}
Base *p = new Derived; // 如果Base::~Base不是虚函数
delete p; // 传入`delete(void *rawMem, std::size_t size)`的`size == sizeof(Base)`。
本文地址:http://harttle.com/2015/09/20/effective-cpp-51.html
Item 51:写new和delete时请遵循惯例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。