1

我在 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

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

4

1 回答 1

9

当然有std::bad_alloc抛。你自己的代码抛出它

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

于 2017-10-25T06:25:57.277 回答