C++ "new" does not return 0 ("NULL") on failure!
..unless you explicitly tell it not to thrown an exception by using std::nothrow. The default behaviour for new is to throw an exception on failure. If a program does not expect (catch) the exception, it will be terminated when new fails (look up the try and catch keywords for more information on exceptions).
Demonstration 1 - How not to use "new"
The example below shows an erroneous program. Please compile it and run the program from the command-line. It demonstrates what happens when an exception goes uncaught, as in this case when we allocate more memory than the system is able to offer. What will happen here is that the program will be terminated instead of continuing its normal execution!
// Demonstration 1 - How not to use "new"
#include <iostream>
int signed main ();
int signed main ()
{
int signed * pais;
pais = new int signed [-1]; // error: exception not expected
if (pais) pais[0] = 10;
delete [] pais;
std::cout << "Is this part reached?" << std::endl;
return 0;
}
The error here is that the program does not expect new to throw an exception, neither does it explicitly tell new not to throw an exception, which brings us to the next demonstration. (Note that delete accepts the value 0, but in this example it is irrelevant, because program execution would never get this far.)
Demonstration 2 - Forcing "new" to return 0 ("NULL") on failure
If you want new to return 0 ("NULL") on failure, you have to explicitly tell it not to throw an exception. To do this, simply include the header "new", which defines the std::nothrow option, and then add "(std::nothrow)" as shown below.
// Demonstration 2 - Forcing "new" to return 0 ("NULL") on failure
#include <new>
#include <iostream>
int signed main ();
int signed main ()
{
int signed * pais;
pais = new (std::nothrow) int signed [-1]; // ok: exception never thrown
if (pais) pais[0] = 10;
delete [] pais;
std::cout << "Is this part reached?" << std::endl;
return 0;
}
Now the program works as the programmer expected! Note that delete accepts the value 0 ("NULL").
本文探讨了C++中使用new操作符进行内存分配时的行为差异:默认情况下遇到失败会抛出异常,以及如何通过使用std::nothrow选项来避免异常抛出并返回0(NULL)。演示了两种情况下的具体实例。
4514

被折叠的 条评论
为什么被折叠?



