首页 > 解决方案 > 在每个新对象之后检查 NULL 是否有任何目的?

问题描述

假设这里 new 将引发异常。

是否会检查对象 new 下方的 NULL 条件,因为它会返回异常,那么在每个新对象之后进行此 NULL 检查是否有意义?

#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();
}

标签: c++c++11c++14

解决方案


推荐阅读