zoukankan      html  css  js  c++  java
  • nothrow new和 new

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

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

  • 相关阅读:
    转 windows查看端口占用命令
    servlet 让浏览器输出中文,并成功打印出来.2种方法
    ctrl+shift+i eclipse快捷键,debug时显示全黑屏
    转 一台电脑安装多个tomcat
    如何从windows中拷贝文件到linux (ubuntu)??
    Eclipse Java注释模板设置简介,更改字体大小
    sikuli 如何 清空文本框中的内容??解决方法!
    servlet 中通过response下载文件
    servlet乱码 解决方法 2种方法
    关于JAVA路径 问题
  • 原文地址:https://www.cnblogs.com/xuxm2007/p/2121235.html
Copyright © 2011-2022 走看看