ABCplus
ABCplus

Reputation: 4021

Could a 'new' statement fail without throwing an exception?

Consider the following code snippet:

try{
LibObject* obj = new LibObject();
if (!obj)
    return 0;
}catch(...){
    return 0;
}
return 1;

I don't know the implementation of the LibObject since it comes from an external library.

Generally speaking, could have any sense to check if the new object instance (obj) is NULL? Or the check is simply unuseful?

Could a new statement return a NULL object without throwing an exception?

Upvotes: 1

Views: 171

Answers (1)

amchacon
amchacon

Reputation: 1961

LibObject* obj = new LibObject(); 

Don't use parenthesis here. And if you don't want alloc exception, you should use std::nothrow

LibObject* obj = new(std::nothrow) LibObject;
if (obj == nullptr) return 0;
else return 1;

This is the correct syntax. You can find a reference here:

http://www.cplusplus.com/reference/new/nothrow/

Upvotes: 1

Related Questions