曲径通幽论坛

标题: new 与 异常 [打印本页]

作者: beyes    时间: 2011-11-20 21:51
标题: new 与 异常
使用 new 发生失败时会抛出一个异常,在标准 C++ 中是抛出一个 bad_alloc 类型异常,如果程序中不能捕捉这个异常,那么程序将被终止。要使用这种类型的异常,必须包含 <new> 头文件。

下面程序演示使用 try/catch 来监控运算符 new 在内存分配失败时产生的异常:
[C++] 纯文本查看 复制代码
#include <iostream>
#include <new>


using namespace std;


int main()
{
        int *p, i;


        try {
                p = new int[9999999999999];
        }
        catch (bad_alloc xa) {
                cout << "Allocation failure.\n";
                return 1;
        }


        delete [] p;


        cout << "Allocation OK, has deleted the allocated memory.\n";


        return 0;
}

编译时会发出警告,但仍然能生成可执行文件:
g++ newexp.cc -o newexp
newexp.cc:11:15: warning: integer constant is too large for its type [enabled by default]
运行输出:
./newexp
Allocation failure.

作者: beyes    时间: 2011-11-20 22:13
标题: 不抛出异常的 new (nothrow)
在标准 C++ 中,当内存分配失败时,new 也可以不用抛出一个异常,而是返回一个空值。使用现代编译器编译以前的代码时,new 的这种用法很有用。new 的这种形式如下所示:
p_var = new(nothrow) type;
上面,p_var 是一个指向 type 类型的指针变量。由于 nothrow 形式的 new 在内存分配失败时返回空值,所以它能够兼容旧有的代码。

示例代码:
[C++] 纯文本查看 复制代码
#include <iostream>
#include <new>
using namespace std;


int main()
{
        int *p, i;
        p = new(nothrow) int[9999999999990000000000000];


        if (!p) {
                cout << "Allocation failure.\\n";
                return 1;
        }


        cout << "Allocation OK.\\n";
        delete [] p;


        return 0;
}

编译时会发出警告,但仍可生成可执行文件:
g++ noexp.cc -o noexp
noexp.cc:8:23: warning: integer constant is too large for its type [enabled by default]
运行输出:
[quoute]./noexp
Allocation failure.[/quote]
从程序中看到,当使用 nothrow 方法时,在每个内存分配请求后,必须检查 new 返回的指针的有效性。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2