如果我的 C++“新"内存分配失败,如何找出返回值? [英] How to find out the return value if my C++ “new” memory allocation failure?

查看:34
本文介绍了如果我的 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++“新"内存分配失败,如何找出返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆