它是有用的测试“新”的返回。在C ++? [英] Is it useful to test the return of "new" in C++?

查看:116
本文介绍了它是有用的测试“新”的返回。在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常不会在C ++中测试新的,我想知道为什么。



Foo * f = new Foo;



// f假定为已分配,为什么通常没有人测试新的返回? / p>

解决方案

根据当前标准, new 从不返回 NULL 抛出一个std :: bad_alloc。如果你不想要新的(根据旧的标准),而是返回NULL,你应该调用它后缀用(std :: nothrow)

  Foo * foo = new(std :: nothrow)Foo; 

当然,如果你有一个非常老的或可能破碎的工具链,可能不遵循标准。 / p>

I usually never see test for new in C++ and I was wondering why.

Foo *f = new Foo;

// f is assumed as allocated, why usually, nobody test the return of new?

解决方案

As per the current standard, new never returns NULL, it throws a std::bad_alloc instead. If you don't want new to throw(as per the old standard) but rather return NULL you should call it by postfixing it with "(std::nothrow)". i.e.

Foo* foo = new (std::nothrow) Foo;

Of course, if you have a very old or possibly broken toolchain it might not follow the standard.

这篇关于它是有用的测试“新”的返回。在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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