???????????????“?????”(mixin-style)??????????????????????????????????——??????????????????new-handler???????????????????????????????е??????????set_new_handler??operator new???????????????????????????в????currenthandler???????????????????????????????????????????????????????????????????κ??????????


template<class t> // ????set_new_handler????
class newhandlersupport { // ?????”?????
public:
 static new_handler set_new_handler(new_handler p);
 static void * operator new(size_t size);

private:
 static new_handler currenthandler;
};

template<class t>
new_handler newhandlersupport<t>::set_new_handler(new_handler p)
{
 new_handler oldhandler = currenthandler;
 currenthandler = p;
 return oldhandler;
}

template<class t>
void * newhandlersupport<t>::operator new(size_t size)
{
 new_handler globalhandler =
  std::set_new_handler(currenthandler);
 void *memory;
 try {
  memory = ::operator new(size);
 }
 catch (std::bad_alloc&) {
  std::set_new_handler(globalhandler);
  throw;
 }
 
 std::set_new_handler(globalhandler);
 return memory;
}
// this sets each currenthandler to 0

template<class t>
new_handler newhandlersupport<t>::currenthandler;

????????????????x????set_new_handler?????????????x??newhandlersupport<x>??У?
// note inheritance from mixin base class template. (see
// my article on counting objects for information on why
// private inheritance might be preferable here.)
class x: public newhandlersupport<x> {

...  // as before?? but no declarations for
};  // set_new_handler or operator new
 


???????x????????????????????????Щ?????????????????????????Щ??????????????????????????

???????set_new_handler???????治?????????????????????????????new???????try?????????????????newhandlersupport???????????????κ???????????????new-handler????????“?????”???в???????????????????????????????????????????????????????43??

????1993?????c++?????????????????operator new?????0?????????????operator new???std::bad_alloc???????c++????????????????????1淶?д???c++??????????????Щ???е????????0?淶??????????????????????????operator new???????????0???????Щ????????“?????”???????????ù????throw???????????new???????????nothrow????


class widget { ... };

widget *pw1 = new widget;// ??????????std::bad_alloc if

if (pw1 == 0) ... // ????????????
 widget *pw2 = new (nothrow) widget;  // ???????????0
 
if (pw2 == 0) ... // ????????????
 


????????????“????”????????????????new????“?????”?????new?????????????????????????????????????????????set_new_handler?????????????????????á?