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

Linux g++ new (std::nothrow) does work

我在 new 运算符中使用 C++ 常量值 std::nothrow 以避免失败时出现异常,而 return 则为 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

从输出消息来看,抛出了一个异常;但我希望它不应该,而是期望空指针 return 。 谁能帮我解决这个问题。谢谢

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

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