2

ISO C++ says...

Fred * p = new Fred();  // No need to check if p is null

No need to check p for null why is that so ?

1 Answers1

12

The reason is that this type of call to new results in an exception being raised if there is a memory allocation error. So there is no situation in which new would return NULL/nullptr when invoked like this.

It you want new to return NULL instead of throwing an exception, you can invoke it with std::nothrow:

Fred* p = new (std::nothrow) Fred();

Here, it would make sense to check against NULL/nullptr.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480