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++“新"内存分配失败,如何找出返回值?
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
