看到effective c++中内存分配的处理,编写代码便于以后的理解:
1. 基本版:
msdn上这么解释:
Call the C++ _set_new_handler function to specify an exception-handling function that is to gain control if the new operator fails to allocate memory. If new fails, the run-time system automatically calls the exception-handling function that was passed as an argument to _set_new_handler. _PNH, defined in NEW.H, is a pointer to a function that returns type int and takes an argument of type size_t. Use size_t to specify the amount of space to be allocated.
_set_new_handler is essentially a garbage-collection scheme. The run-time system retries allocation each time your function returns a nonzero value and fails if your function returns 0.
2. effective c++上提供的一条有效的建议是提供一个类作为基类,这样子类
等出现内存分配失败时,均可以用到,也可以写为模板类,代码如下:
为了让内存尽快耗完,我在class内部定义一个大block的内存块,这样就能在
main中定义到第二个变量时变出现了内存分配失败的情形,其实在NonMemory这样的函数中,
应该尽量做到垃圾内存回收,并且返回1,这样的话,会让分配失败后,继续调用分配内存,这样才是
我们编程人员想要的结果。以上纯为effective c++中“预先准备内存不足”这一章节的个人理解描述。