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

问题描述 投票:0回答:1

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

int* i = new int();

我无法检查我的指针是否为 0。

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

c++ memory
1个回答
10
投票

阅读文档: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
© www.soinside.com 2019 - 2024. All rights reserved.