为什么要避免在新的ISO C++之后检查null

RAV*_*tel 2 c++ memory null

ISO C++说......

Fred * p = new Fred();  // No need to check if p is null
Run Code Online (Sandbox Code Playgroud)

不需要检查p为null为什么会这样?

jua*_*nza 12

原因是new如果存在内存分配错误,这种类型的调用会导致异常.因此,没有这样的情况下new会返回NULL/ nullptr调用.

你想要new返回NULL而不是抛出异常,你可以用std::nothrow以下方法调用它:

Fred* p = new (std::nothrow) Fred();
Run Code Online (Sandbox Code Playgroud)

在这里,检查NULL/是有意义的nullptr.