Cap*_*emo 11 c++ mingw allocation exception new-operator
在我的一个学校项目中,我被要求创建一个不使用STL的程序.
在程序中我使用了很多
Pointer* = new Something;
if (Pointer == NULL) throw AllocationError();
Run Code Online (Sandbox Code Playgroud)
我的问题是关于分配错误:
1.当分配失败时,是否有新的自动异常?
2.如果是这样,如果我没有使用STL(
3 #include "exception.h)我怎么能抓住它?是否
正在使用NULL测试?
谢谢.
我在Windows 7上使用eclipseCDT(C++)和MinGW.
bcs*_*hes 14
是的,如果新运算符无法分配内存,它将自动抛出异常.
除非你的编译器以某种方式禁用它,否则new将永远不会返回NULL指针.
它引发了一个bad_alloc例外.
还有一个nothrow你可以使用的新版本:
int *p = new(nothrow) int(3);
Run Code Online (Sandbox Code Playgroud)
如果无法分配内存,则此版本返回空指针.但也请注意,这并不能保证100%nothrow,因为对象的构造者仍然可以抛出异常.
更多信息:http://msdn.microsoft.com/en-us/library/stxdwfae(VS.71).aspx
- 分配失败时,new 是否会引发自动异常?
- 如果是这样,如果我不使用 STL (#include "exception.h),我怎么能抓住它
是的。请参阅此示例。它还演示了如何捕获异常!
try
{
int* myarray= new int[10000];
}
catch (bad_alloc& ba)
{
cerr << "bad_alloc caught: " << ba.what() << endl;
}
Run Code Online (Sandbox Code Playgroud)
从这里:http : //www.cplusplus.com/reference/std/new/bad_alloc/
3 . 使用 NULL 测试就够了吗?
这不是必需的,除非您使new运算符过载!
| 归档时间: |
|
| 查看次数: |
47432 次 |
| 最近记录: |