如果我的 C++“新"内存分配失败,如何找出返回值?

2022-01-11 00:00:00 operating-system memory-management c++

在 C 语言中,人们经常在使用 malloc 后检查空指针.但是,在 C++ 中,我们将使用new".根据我之前的问题这里,我到了知道 C++ 中的 new 会在内存分配失败时给出两个可能的返回值:

In C, people often check null pointers after using malloc. However, in C++, we will use "new". Based on my previous question here, I get to know that new in C++ will give two possible return values on memory allocation failure:

抛出版本:不返回任何内容,如果我尝试使用(读/写)分配的变量,程序将崩溃.

The throwing version: return nothing, program will crash if I try to use (read/write) the variable that is allocated.

非抛出版本:返回 NULL 指针.

The non-throwing version: return NULL pointer.

我怎样才能知道我的程序正在使用哪个版本?(是否有任何一般步骤需要寻找,因为我不想提及我正在使用的操作系统以避免复杂化)

How can I find out which version my program is using? (Is there any general steps to look for since I would rather not mention the OS I am using to avoid complication)

推荐答案

标准表明不合格的 new 将是抛出版本,尽管一些(通常是嵌入式)系统提供编译器选项来改变它默认行为.

The standard indicates that an unqualified new will be the throwing version, although some (typically embedded) systems offer compiler options to change that default behavior.

如果您看到 new (std::nothrow) T,那么这是在失败时返回 null 的非抛出版本.

If you see new (std::nothrow) T then that's the non-throwing version that returns null on failure.

相关文章