LoginSignup
5
5

More than 5 years have passed since last update.

[C++] new & new(nothrow)

Posted at

If there are not enough memory when new some data in C++, it will have a exception.

Do something like this:

long long n = 1LL << 63LL;
int *p = new int[n];

Then you will get a exception like this:

libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc

But if you use the new(nothrow), instead of exception, you will get a null pointer.

long long n = 1LL << 63LL;
int *p = new(nothrow) int[n];
if (p == nullptr) cout << "Null Pointer" << endl;

Output:

Null Pointer
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5