How to find out the return value if my C++ “new” memory allocation failure?(如果我的 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.
这篇关于如果我的 C++“新"内存分配失败,如何找出返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果我的 C++“新"内存分配失败,如何找出返回值?


- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01