A pointer returns a new check in C ++

What is the best way to check for a pointer return to a new operator I can see the following type of code. Suppose I have a 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 ) { } 
+4
source share
4 answers

You do not check new for null, it throws an exception std::bad_alloc in case of its failure.
This way you handle the exception.

Of course, this rule applies if you are not using the nothrow new version.

  try { Test *ptr = new Test; } catch (std::bad_alloc &e) { cout << "new Failed"; } 
+9
source

By default, new should throw a bad_alloc exception, so no checks are required.

VC6, on the other hand, returns 0 on bad_alloc, in which case Type 3 should be fine in cases where you don't have nullptr (which is in the C ++ 11 standard)

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

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

In any case, remember that you do not need to catch every bad_alloc where it was thrown. You better catch him where you can react to him (free memory or skillfully gracefully).

+1
source

Assuming your allocator / implementation returns 0 instead of throwing, I think this is the best:

 Test* const ptr(new Test); if (0 == ptr) { // uh-oh } 

0 common in C ++, and you were not mistaken in assigning a pointer with a constant on the left.

If it is local to if , you might like the following:

 if (Test* const ptr = new Test) { // use it } 
0
source

Always try lhs to be constant for the == operator

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

Here, by mistake, if you write = instead of ==, this will give a compilation error.

But if you write if (ptr = NULL), it will not give any error, NULL will be assigned to ptr

0
source

Source: https://habr.com/ru/post/1392885/


All Articles