问题描述
我通常不会在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 ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!