zoukankan      html  css  js  c++  java
  • C++11 不抛异常的new operator

    在google cpp style guide里面明确指出:we don't use exceptions

    C++11的noexcept关键字为这种选择提供了便利。

    C++11以前,提及malloc和new的区别,总是会强调由malloc返回的指针需要检查是不是null,因为空间分配可能

    失败,而由new返回的指针不用检查,因为如若分配失败,它会抛出异常,现在又提供了std::nothrow,使得我们

    可以人让new不抛异常,而是返回nullptr表示分配失败,这在需要禁用异常的场合显得很实用,具体的例子如下:

    // operator new example
    #include <iostream>     // std::cout
    #include <new>          // ::operator new
    
    struct MyClass {
        int data[100];
        MyClass() {std::cout << "constructed [" << this << "]
    ";}
    };
    
    int main () {
    
        std::cout << "1: ";
        MyClass * p1 = new MyClass;
        // allocates memory by calling: operator new (sizeof(MyClass))
        // and then constructs an object at the newly allocated space
    
        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::cout << "3: ";
        new (p2) MyClass;
        // does not allocate memory -- calls: operator new (sizeof(MyClass),p2)
        // but constructs an object at p2
    
        // Notice though that calling this function directly does not construct an object:
        std::cout << "4: ";
        MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
        // allocates memory by calling: operator new (sizeof(MyClass))
        // but does not call MyClass's constructor
    
        delete p1;
        delete p2;
        delete p3;
    
        return 0;
    }

    可见,只要把原来我们习惯的new T,改成 new (std::nothrow) T,就能使得我们的new expression不抛异常

  • 相关阅读:
    Sublime Text 2.0.2 注册码激活
    常用的接口查询,会持续更新中……
    JavaScript获取访问设备信息
    Param指南
    HTML5调用手机摄像头,仅仅支持OPPOHD浏览器
    GET传值
    关于IE缓存
    浏览器的类别及介绍
    JS调用C#中的变量
    在VS2012中设置默认启动
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/5070265.html
Copyright © 2011-2022 走看看