C++ "new" does not return 0 ("NULL") on failure!

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").

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值