I know that quite a few C ++ frequently asked questions (and the answers here are on SO) say that there is no need to check the return value of a simple new expression for null, since a simple new expression indicates errors, throwing exceptions. They basically claim that a simple new expression never returns null. (By "simple new expression" I mean a new expression that is not nothrow ).
However, despite the fact that it looked like a very simple question, I suddenly realized that I did not understand what specific assumptions they made (if any) when they gave this answer.
In particular, I am wondering if I can overload the basic form of the ::operator new form to always return a null pointer, and therefore expect all simple new expressions that use this operator to also return null pointers.
According to the language specification, if my ::operator new declared as low-key, then I can / should indicate a memory allocation error by returning a null pointer. So let's do just that
void *operator new(size_t s) throw() { return 0; } int main() { int *i = new int; }
In my experiments, the above new expression successfully returns a null pointer. So, am I breaking any rules in the above code or not? Is it legal to declare a simple ::operator new as non-throwing?
And if the above code is fine, then I would suggest that when someone claims that a simple new βnever returns a null pointerβ, they do it under the assumption that the version ::operator new provided in the standard library was replaced by. Is this a presumption right?
source share