No! (But if you have an ancient, stone-age compiler, you may have to
force the new operator to throw an
exception if it runs out of memory.)
It turns out to be a real pain to always write explicit NULL tests after
every new allocation. Code like the following is very tedious:
Fred* p = new Fred();
if (p == NULL) ← only needed if your compiler is from the Stone Age!
throw std::bad_alloc();
If your compiler doesn't support (or if you refuse to use)
exceptions, your code might be even more tedious:
Fred* p = new Fred();
if (p == NULL) { ← only needed if your compiler is from the Stone Age!
std::cerr << "Couldn't allocate memory for a Fred" << std::endl;
abort();
}
Take heart. In C++, if the runtime system cannot allocate
sizeof(Fred) bytes
of memory during
p = new Fred(), a
std::bad_alloc exception will be
thrown. Unlike
malloc(),
new never returns
NULL!
Therefore you should simply write:
Fred* p = new Fred(); ← no need to check if p is NULL
However, if your compiler is ancient, it may not yet support this. Find out by
checking your compiler's documentation under "
new". If it is ancient,
you may have to
force the compiler to
have this behavior.
Note: If you are using Microsoft Visual C++, to get new to throw an
exception when it fails
you
must #include some standard header in at least one of your .cpp files.
For example, you could #include <new> (or <iostream> or
<string> or ...).