Will new operator return NULL? [duplicate]

空扰寡人 提交于 2019-12-03 20:37:16

问题


Possible Duplicate:
Will new return NULL in any case?

Say i have a class Car and i create an object

Car *newcar  = new Car();
if(newcar==NULL) //is it valid to check for NULL if new runs out of memory
{
}

回答1:


On a standards-conforming C++ implementation, no. The ordinary form of new will never return NULL; if allocation fails, a std::bad_alloc exception will be thrown (the new (nothrow) form does not throw exceptions, and will return NULL if allocation fails).

On some older C++ compilers (especially those that were released before the language was standardized) or in situations where exceptions are explicitly disabled (for example, perhaps some compilers for embedded systems), new may return NULL on failure. Compilers that do this do not conform to the C++ standard.




回答2:


No, new throws std::bad_alloc on allocation failure. Use new(std::nothrow) Car instead if you don't want exceptions.




回答3:


By default C++ throws a std::bad_alloc exception when the new operator fails. Therefore the check for NULL is not needed unless you explicitly disabled exception usage.



来源:https://stackoverflow.com/questions/3389420/will-new-operator-return-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!