Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer return by new check in C++

Tags:

c++

What is the best way to check the pointer return by a new operator I see following type of code. Assume I have class Test

Type 1

Test *ptr = new Test;
if ( ptr == NULL ) {
}

Type 2

Test *ptr = new Test;
if ( !ptr ) {
}

Type 3

Test *ptr = new Test;
if ( ptr == (Test*)0 ) {
}
like image 985
Avinash Avatar asked Dec 22 '22 03:12

Avinash


2 Answers

You do not check new for null it throws an exception std::bad_alloc in case it fails.
So you handle the exception.

Ofcourse, the above rule applies if you are not using the nothrow version of new.

 try
  {
    Test *ptr = new Test;
  }
  catch (std::bad_alloc &e)
  {
    cout << "new Failed";
  }
like image 70
Alok Save Avatar answered Dec 24 '22 03:12

Alok Save


By default new should throw an bad_alloc exception, so no checks should be necessary.

On the other hand VC6 do return 0 on a bad_alloc in that case Type 3 should be perfectly fine in cases where you do not have nullptr (which is in the C++11 standard)

Another way to be able to test for NULL is to call new with std::nothrow:

ptr = new(std::nothrow) Test();

In any case remember that you do not have to catch every bad_alloc where it is thrown. You are better off catching it where you can respond to it (free memory or die gracefully).

like image 27
daramarak Avatar answered Dec 24 '22 03:12

daramarak