The problem with C code is that you have to check the return value of the function to make sure that they work correctly. But a lot of code was written that did not check the return value and, as a result, exploded very well when you least expected it.
In the worst case, it doesn't even work right away, but continues to interrupt a memory failure at some point miles downstream of the error.
Thus, exceptions were born in C ++.
Now that there is an error, the code does not continue (thus, memory is not corrupted), but unwinds the stack (potentially forcing the application to exit). If you handle this problem, you must explicitly add code to deal with the situation before proceeding. Thus, you cannot accidentally forget not to check the error state; You either check this, or the application closes.
Using the new is consistent with this design.
If you fail to allocate memory, you must explicitly handle the error.
You cannot forget to check the NULL pointer. Thus, you cannot go and ruin the memory by accidentally using the NULL pointer.
In addition, when allocating static memory, that is, on the stack, is there an exception if we run out of memory?
Unfortunately, you cannot rely on this.
The implementation is determined by what happens when the stack overflows. On many systems, it is not even possible to detect a situation leading to memory corruption and, possibly, to the end of a failure.
Note
If you #include <new> then there is no new version of the cast that you can use that returns NULL when there is no remaining memory. This is best avoided unless you have a specific need.