简体   繁体   English

C ++异常处理和内存动态分配

[英]C++ Exception handling and dynamic allocation of memory

I'm learning exception handling in C++, here is how I tried to apply it on dynamic allocation memory: 我正在学习C ++中的异常处理,以下是我尝试将其应用于动态分配内存的方法:

#include <iostream>

using namespace std;

int main()
{
    const char * message[] = {"Dynamic memory allocation failed! "};
    enum Error{
        MEMORY
    };

    int * arr, length;
    cout << "Enter length of array: " << endl;
    cin >> length;

    try{
        arr = new int[length];
        if(!arr){
            throw MEMORY;
        }
    }
    catch(Error e){
        cout << "Error!" << message[e];
    }
    delete [] arr;
}

It doesn't work as it should, If I enter some huge number for length, instead of showing message "Dynamic memory allocation failed! " (without quotes) I got: 它不能正常工作,如果我输入一些巨大的长度,而不是显示消息“动态内存分配失败!”(没有引号)我得到:

terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc 抛出'std :: bad_alloc'的实例后调用terminate():std :: bad_alloc

This application has requested the Runtime to terminate it in an unusual way. 此应用程序已请求Runtime以不寻常的方式终止它。 Please contact the application's support team for more information. 有关更多信息,请联系应用程序的支持团队。

Process returned 3 (0x3) execution time : 3.835 s Press any key to continue. 进程返回3(0x3)执行时间:3.835 s按任意键继续。

Any idea? 任何的想法?

Operator new itself throws an error. 运算符new本身会抛出错误。 And it's error is not of type Error you specified, so if memory won't be able to be allocated, then your if statement will never be executed, because exception will already be thrown. 并且它的错误不是你指定的类型Error,所以如果无法分配内存,那么你的if语句将永远不会被执行,因为异常将被抛出。

You can delete block with if and try to catch exception, that is thrown by new operator. 您可以使用if删除块并尝试捕获由new运算符抛出的异常。 Alternatively use std::nothrow 或者使用std::nothrow

 arr=new (std::nothrow)[length];

operator to allocate memory 运算符分配内存

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM