gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:24:57 26 4
gpt4 key购买 nike

我在 new 运算符中使用 C++ 常量值 std::nothrow 以避免失败时出现异常,而是返回一个空值。但是正如我所尝试的那样,这似乎不适用于我的环境,即 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

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

最佳答案

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

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

关于c++ - Linux g++ new (std::nothrow) 确实有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46925296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com