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不抛异常

  • 相关阅读:
    VM环境安装Linux系统
    设置ShowDialog
    sqlserver同步表的脚本
    C#winform设置DateTimePicker的时间格式
    C#winform解析marc显示在datagridview中以及marc卡片显示
    C#实现图书馆程序导入ISO-2709格式(MARC)功能
    时间格式转换+固定字段加空格
    sqlserver 保留小数方法
    winform的datagridview单元格输入限制和右键单击datagridview单元格焦点跟着改变
    怎么查看那个端口被占用
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/5070265.html
Copyright © 2011-2022 走看看