Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using new and be able to check the pointer for 0 (null)

Tags:

c++

I was told that by doing,

int* i = new int();

I would not be able to check my pointer for 0. new send a exception in case it fails. But what if I don't want to use exceptions for reasons. Is there any way to check if my pointer is correctly allocated ?

like image 936
nikau6 Avatar asked Dec 24 '22 21:12

nikau6


1 Answers

Read the doc: http://www.cplusplus.com/reference/new/operator%20new/

(2) nothrow allocation Same as above (1), except that on failure it returns a null pointer instead of throwing an exception.

As well as example:

  std::cout << "2: ";
  MyClass * p2 = new (std::nothrow) MyClass;
      // allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
      // and then constructs an object at the newly allocated space
like image 57
NoDataFound Avatar answered Jan 18 '23 19:01

NoDataFound