C ++中的分配异常错误 [英] Bad allocation exceptions in C++

查看:157
本文介绍了C ++中的分配异常错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的学校项目中,我被要求创建一个不使用STL的程序。

在程序中我使用了

  Pointer * = new Something; 
if(Pointer == NULL)throw AllocationError();

我的问题是关于分配错误:

1.是否有自动异常

2.如果是这样,如果我不使用STL( #includeexception.h

3.使用NULL测试enugh?



谢谢。

我使用eclipseCDT(C ++)

$ p

解决方案

是的,如果不能分配内存,新操作符将自动抛出异常。 p>

除非你的编译器以某种方式禁用它,否则新的将永远不会返回一个NULL指针。



它抛出一个 bad_alloc 例外。



还有一个 nothrow 您可以使用:

  int * p = new(nothrow)int(3); 

如果内存不能被分配,这个版本会返回一个空指针,但是这并不能保证100% not hrow ,因为对象的construtor仍然可以抛出异常。



更多的信息: http://msdn.microsoft.com/en-us/library/stxdwfae(VS.71).aspx


In a school project of mine I was requested to create a program not using STL.
In the program I use alot of

Pointer* = new Something;
if (Pointer == NULL) throw AllocationError();

My question is about allocation errors:
1. is there an automatic exception thrown by new when allocation fails?
2. if so how can I catch it if I'm not using STL (#include "exception.h)
3. is using the NULL testing enugh?

thank you.
I'm using eclipseCDT(C++) with MinGW on windows 7.

解决方案

Yes, the new operator will automatically thrown an exception if it cannot allocate the memory.

Unless your compiler disables it somehow, the new will never return a NULL pointer.

It throws a bad_alloc exception.

Also there is a nothrow version of new that you can use:

int *p = new(nothrow) int(3);

this version returns a null pointer if the memory cannot be allocated. But also note that this does not guarantee a 100% nothrow, because the construtor of the object can still throw exceptions.

Bit more of information: http://msdn.microsoft.com/en-us/library/stxdwfae(VS.71).aspx

这篇关于C ++中的分配异常错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆