nothrow——详解

发布时间:2023-05-19

一、nothrowing

nothrowing是C++的一个关键字,用于指定调用new操作符时的异常处理方式。当使用nothrowing参数时,如果内存分配失败,new操作符不会抛出异常,而是返回一个空指针。与之相对的是使用普通的new操作符,如果它无法为对象分配足够的内存,那么就会抛出一个std::bad_alloc类型的异常。

#include<iostream>
using namespace std;
int main() {
    int *p;
    p = new (nothrow) int[100000000000];
    if (p==NULL) cout << "内存分配失败";
    else cout << "内存分配成功";
    return 0;
}

在上述的代码中,由于所需的内存过大,程序无法从操作系统中获得足够的内存,所以没有内存被分配给指针p。如果没有使用nothrow,这段程序将会抛出一个std::bad_alloc异常。

二、nothrow

在C中,如果内存不足以分配对象,则new操作符会引发std::bad_alloc异常,然而,通过使用nothrow,我们可以避免产生这些异常。在C中,当nothrow作为new的第二个参数传递时,它告诉new操作符,如果内存不足,则返回一个NULL指针而非抛出异常。例如:

#include<iostream>
using namespace std;
int main() {
    int *p;
    p = new(nothrow) int[100000000000];
    if (p==NULL) cout << "内存分配失败";
    else cout << "内存分配成功";
    return 0;
}

当内存不足时,该程序将输出“内存分配失败”。

三、怎么读

在C++程序中,可以按照以下方式发音:no-throw。发音时,声调应落在's'和't'之间的元音上。

四、nothrow new

nothrow和nothrow new之间的区别是:若只使用nothrow,则会返回一个NULL指针;使用nothrow new,则不会返回NULL指针,而是返回一个指向失败的new操作的指针。例如:

#include<iostream>
using namespace std;
int main() {
    int *p;
    p = new(nothrow) int[100000000000];
    if (p==NULL) cout << "内存分配失败";
    else cout << "内存分配成功";
    delete[] p;
    return 0;
}

此程序将输出“内存分配成功”,然而,在编写代码时,您应该避免在同一程序中同时使用nothrow和nothrow new。

五、nothrowing怎么读

nothrowing是C++的一个关键字,发音时,应该拼读new和throwing之间的元音。在此单词中,'g'不发音。

六、nothrow翻译

上文中提到的“no-throw”表明其使用的目的,即使用此关键字时,将不会抛出一个std::bad_alloc类型的异常。

七、nothrow用法

使用一些其他的new版本时,如在STL中,使用nothrow能够有效避免异常。例如,当使用vector时,如果它无法为元素分配足够的内存,就会抛出异常。使用nothrow分配内存可避免中断程序的执行。例如:

#include<iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> v;
    try {
        for (int i=0; i<1000000000; i++)
            v.push_back(i);
    }
    catch(...) {
        cout << "内存分配失败";
    }
    return 0;
}

当数据量过大时,该程序将输出“内存分配失败”。但是,如果我们使用nothrow,则可以避免该程序抛出异常。例如:

#include<iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> v;
    for (int i=0; i<1000000000; i++) {
        int *p = new (nothrow) int(1);
        if (p==NULL) {
            cout << "内存分配失败";
            break;
        }
        v.push_back(*p);
    }
    return 0;
}

该程序将输出“内存分配失败”,但是可以在push_back函数之前使用new(nothrow)为元素分配内存。