jbu*_*jbu 12 c++ memory allocation exception
我已经看到资源显示了两种分配内存的方法,同时确保有足够的内存来完成操作.
1)在try/catch中包装'new'操作,因为它将返回std :: bad_alloc(?)
try { ptr = new unsigned char[num_bytes]; } catch(...) {}
Run Code Online (Sandbox Code Playgroud)
2)在'new'操作后检查指定的指针是否为null.
ptr = new unsigned char[num_bytes]; if(ptr == NULL) { ... }
Run Code Online (Sandbox Code Playgroud)
哪一个是对的?他们都工作吗?我是否需要同时做1和2?
谢谢,
JBU
Naw*_*waz 17
如果您使用的标准实现new引发异常,那么第一个是正确的.
如果您使用的话,也可以使用第二个nothrow:
ptr = new (nothrow) unsigned char[num_bytes];
if(ptr == NULL) { ... }
Run Code Online (Sandbox Code Playgroud)
一个不成功的分配[使用new]抛出std::bad_aloc,所以第一个是正确的.
第二个用于c代码,当使用malloc[因为C中没有异常时,NULL用于表示分配失败].
在使用时new,if语句永远不会产生true,因为如果分配失败 - 将抛出异常,并且不会到达if语句.当然,当分配成功时,if语句将产生错误.
| 归档时间: |
|
| 查看次数: |
521 次 |
| 最近记录: |