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

查看:106
本文介绍了如果我的C ++“新”内存分配失败,如何找出返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C中,人们通常在使用malloc后检查空指针。但是,在C ++中,我们将使用new。根据我上一个问题这里,我得到知道新的C ++将给内存分配失败的两个可能的返回值:

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:

抛出的版本:return nothing,如果我尝试使用)分配的变量。

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天全站免登陆