使用 new 并能够检查指针是否为 0(空)
Using new and be able to check the pointer for 0 (null)
有人告诉我,通过这样做,
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
相关文章:
- std::vector::迭代器是否可以合法地作为指针
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 返回指向对象的指针的函数调用是否为 prvalue?
- 对象初始化中是否允许指向此成员的指针?
- 新分配指向函数的指针是否合法?
- 在函数结束后使用指向变量的指针是否安全?
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 如果整数与指针大小相同,则重新解释将整数转换为指针双射是否具有双射作用?
- 是否可以使用函数指针调用虚拟析构函数?
- std::less是否应该允许在编译时比较不相关的指针?
- 是否允许编译器省略对指针的 &* 运算符的组合调用?
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 检查输入 std::array 指针数据是否等于某个常量数组
- 成员访问是否在空指针上定义C++?
- 如果只有 std::auto_ptr 可用,我是否仍应该使用智能指针?
- 是否可以使用指针访问变量以避免直接编辑变量?
- 是否可以仅通过将分配的指针地址存储在C++中来分析内存?
- "this"指针的值在对象的生存期内是否恒定?