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 ) {
}
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";
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With