定制new和delete

条款49:了解new-handler的行为

当operator new无法满足某一内存分配需求时,它会调用一个指定的错误处理函数new-handlernew-handler可能会为operator new找到足够的内存或者其他处理内存不足的情况,

如果new-handler为空,operator new抛出std::bad_malloc。
class NewHandlerHolder {
public:
    explicit NewHandlerHolder(std::new_handler nh)
        : handler(nh) {}

    ~NewHandlerHolder() {
        std::set_new_handler(handler);
    }
private:
    NewHandlerHolder(const NewHandlerHolder&);
    NewHandlerHolder& operator=(const NewHandlerHolder&);
    std::new_handler handler;
};

重载operator new

class Node {
public:
    void* operator new(std::size_t size) {
        /* 设置 new_handler*/
        NewHandlerHolder nhd(std::set_new_handler(outOfMemory));
       
        //NewHandlerHolder nhd(std::set_new_handler(0));  // std::bad_alloc
       
        return ::operator new(size);
    }
    static void outOfMemory() {
        std::cout << "out of Memory" << std::endl;
    }
};

模板化继承

brilliant - P245

template<typename T>  
class NewHandlerSupport 
{  
  public:  
    static std::new_handler set_new_handler( std::new_handler p )throw();  
    static void* operator new( std::size_t size ) throw( std::bad_alloc );  
  private:  
    static std::new_handler currentHandler;  
};  

template<typename T>  
std::new_handler  
NewHandlerSupport<T>::set_new_handler( std::new_handler p ) throw() 
{
    std::new_handler oldHandler = currentHandler;  
    currentHandler = p;  
    return oldHandler;  
}  

template<typename T>  
void* 
NewHandlerSupport<T>::operator*( std::size_t size ) throw( std::bad_alloc ) 
{  
    NewHandlerHolder h(std::set_new_handler(currentHandler));  
    return ::operator new(size);  
}  
class Node : public NewHandlerSupport<Node> {};

继承自 NewHandlerSupport的每个class,拥有实体互异的NewHandlerSupport复件。
Template机制会自动为每一个T生成一个currentHandler

本文固定链接: http://www.js-code.com/cpp/cpp_58585.html