定製new和delete
條款49:瞭解new-handler的行為
當operator new無法滿足某一記憶體分配需求時,它會呼叫一個指定的錯誤處理函式new-handler,
new-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