0

Suppose here new will raise exception.

Will the NULL condition below new of object will ever be checked as on exception it will return , So is there point to have this NULL check after every new?

#include <iostream>
using namespace std;
class Obj
{
    int x;

public:
    Obj() : x(0)
    {
    }
    ~Obj() = default;
};

Obj *CreateObject()
{
    Obj *o = new Obj; //suppose here new will raise exception
    //Will This condition will ever be checked as on exception it will return , SO is there point to have this NULL check ??
    if (!o)
    {
        cout << "Object creation failed";
        return nullptr;
    }
    return o;
}

int main()
{
    CreateObject();
}
Sanjeev
  • 115
  • 7
  • 3
    The `NULL` test is completely useless and should be removed. – prapin Apr 17 '21 at 12:23
  • As you said yourself, the check is irelevant due to the fact that the new operator throws a bad_alloc exception. – Kfir Ventura Apr 17 '21 at 12:24
  • Some compilers allow disabling specific standard C++ features, such as the entire exception throw/catch mechanism or RTTI. For code written to such a "not quite C++" language, then explicitly handling `new` having a `nullptr` result may be necessary. Usually such *not quite C++* is specific to a particular situation (e.g., programming firmware on a controller card, with constraints that preclude some-or-many C++ language features). – Eljay Apr 17 '21 at 12:38

0 Answers0