C++之std::nothrow
来源:互联网 发布:jira类似的软件 编辑:程序博客网 时间:2024/06/03 14:57
标准的new头文件可以定义普通的new,同时,它也可以定义一个变体new操作符,这个操作符叫做nothrownew。普通的new:过去和现在 普通new一个异常的类型std::bad_alloc。这个是标准适应性态。在早期C++的舞台上,这个性态和现在的非常不同;new将返回0来指出一个失败,和malloc()非常相似。
在一定的环境下,返回一个NULL指针来表示一个失败依然是一个不错的选择。C++标准委员会意识到这个问题,所以他们决定定义一个特别的new操作符版本,这个版本返回0表示失败。
一个nothow new语句和普通的new语句相似,除了它的变量将涉及到std::nothrow_t。Class std::nothrow_t在new将按照下面的方式来定义:
按照这个方式,调用nothrow new的代码将可以使用统一的变量名字。比如:
但是,你可以注意到你创建了你自己的nothrow_t对象来完成相同的效应:
在一定的环境下,返回一个NULL指针来表示一个失败依然是一个不错的选择。C++标准委员会意识到这个问题,所以他们决定定义一个特别的new操作符版本,这个版本返回0表示失败。
一个nothow new语句和普通的new语句相似,除了它的变量将涉及到std::nothrow_t。Class std::nothrow_t在new将按照下面的方式来定义:
- class nothrow_t // in namespace std
- {}; //empty class
- Operator nothrow new is declared like this:
- //declarations from <new>
- void * operator new (size_t size, const std::nothrow_t &);
- //array version
- void * operator new[] (size_t size, const std::nothrow_t &);
- In addition, <new> defines a const global object of type nothrow_t:
- extern const nothrow_t nothrow; //in namespace std
按照这个方式,调用nothrow new的代码将可以使用统一的变量名字。比如:
- #include <new>
- #include <iostream> // for std::cerr
- #include <cstdlib> // for std::exit()
- Task * ptask = new (std::nothrow) Task;
- if (!ptask)
- {
- std::cerr<<"allocation failure!";
- std::exit(1);
- }
- //... allocation succeeded; continue normally
但是,你可以注意到你创建了你自己的nothrow_t对象来完成相同的效应:
- #include <new>
- std::nothrow_t nt;
- Task * ptask = new (nt) Task; //user-defined argument
- if (!ptask)
- //...
分配失败是非常普通的,它们通常在植入性和不支持异常的可移动的器件中发生更频繁。因此,应用程序开发者在这个环境中使用nothrow new来替代普通的new是非常安全的。
转载:http://blog.csdn.net/hertz2007/article/details/6629654
- C++之std::nothrow
- C++ 之 std::nothrow
- std::nothrow
- std::nothrow
- std::nothrow
- std::nothrow .
- std::nothrow
- std::nothrow
- std::nothrow
- std::nothrow
- 关于std::nothrow
- new && new(std::nothrow)
- 关于std::nothrow
- new && new(std::nothrow)
- 8.24 std::nothrow
- 关于 new(std::nothrow)
- new(std::nothrow)
- 转载: 关于std: :nothrow
- C++转型之static_cast、dynamic_cast、reinterpret_cast和const_cast
- 高斯消元法求解一元多次方程 C/C++实现
- Makefile常见错误解析 - make: *** No rule to make target 'test1.o', needed by 'test2'. Stop
- 双链表2
- 组合控件的使用
- C++之std::nothrow
- 做人做事
- win7 英文版电脑 不睡眠,不休眠
- TraceTableUnit
- 冒泡排序
- TraceTableUnit2
- jsxon通过JSONStr转换为object
- 在 Oracle Linux 上安装 Shared Folders
- 微软为何收购诺基亚 昔日巨头能摆脱困境吗?