Linux g ++ new(std :: nothrow)确实有效

时间:2017-10-25 06:23:16

标签: c++ nothrow

我在new运算符中使用c ++常量值std :: nothrow以避免失败时出现异常,并返回null。 但是,正如我尝试的那样,在我的环境中似乎无法正常工作的是Linux x86_64上的g ++ 4.4.4。

以下是测试程序和执行结果:

#include <stdlib.h>

#include <new>
#include <iostream>

class TT {
public:
    TT(int size);
    ~TT();
private:
    char * buffer;
};

TT::TT(int size) : buffer(NULL) {
    if (size <= 0) {
        throw std::bad_alloc();
    }

    buffer = (char *)malloc(size);
    if (buffer == NULL) {
        throw std::bad_alloc();
    }
}

TT::~TT() {
    if (buffer != NULL) {
        delete buffer;
    }
}

int main(int argc, char * argv[]) {
    TT * tt = NULL;
    try {
        tt = new  TT(0);
    } catch (std::bad_alloc& ba) {
        std::cout << "tt exception caught" << std::endl;
    }

    tt = new (std::nothrow) TT(0);
    if (tt == NULL) {
        std::cout << "tt is null" << std::endl;
    }
    else {
        std::cout << "tt is not null" << std::endl;
    }

    return 0;
}

执行结果:

$ uname -i
x86_64
$ g++ --version
g++ (GCC) 4.4.4 20100726 (Red Hat 4.4.4-13)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ g++ t.cpp 
$ ./a.out 
tt exception caught
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted

从输出消息中抛出异常;但我希望它不应该,而是预期返回空指针。 任何人都可以帮我解决这个问题。感谢。

1 个答案:

答案 0 :(得分:8)

当然有一个std::bad_alloc被抛出。 您自己的代码抛出

new (std::nothrow)仅指定新表达式的内存分配器不会抛出。但是一旦你的TT对象在那个内存中构建,它仍然会抛出它喜欢的任何异常。