首页 技术 正文
技术 2022年11月10日
0 收藏 589 点赞 3,540 浏览 1091 个字

普通new一个异常的类型std::bad_alloc。这个是标准适应性态。
在早期C++的舞台上,这个性态和现在的非常不同;new将返回0来指出一个失败,和malloc()非常相似。

在内存不足时,new (std::nothrow)并不抛出异常,而是将指针置NULL

在一定的环境下,返回一个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是非常安全的。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,111
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,584
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,431
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,203
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,838
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,922