使用 new 并能够检查指针是否为 0(空)

Using new and be able to check the pointer for 0 (null)

本文关键字:是否 指针 new 检查 使用      更新时间:2023-10-16

有人告诉我,通过这样做,

int* i = new int();

我将无法检查我的指针是否为 0。 new发送异常以防失败。但是,如果我出于某种原因不想使用异常怎么办。有没有办法检查我的指针是否正确分配?

阅读文档:http://www.cplusplus.com/reference/new/operator%20new/

(2)无掷分配 与上述 (1) 相同,不同之处在于失败时它返回空指针而不是引发异常。

以及示例:

  std::cout << "2: ";
  MyClass * p2 = new (std::nothrow) MyClass;
      // allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
      // and then constructs an object at the newly allocated space