On 11/03/2015 05:35 AM, Aurelio Remonda wrote:
Currently, whenever operator new (std::nothrow) fails to allocate memory, it'll
check if there is a new-handler function available. If there is, it'll call
the handler and then try to allocate again. Otherwise, it'll return a null
pointer.
This retrying behavior may not always be desirable. If the handler cannot fix
the memory allocation issue, we may end up being stuck in an infinite loop.
Whereas returning nullptr may be a valid alternative to keep calling the
new_handler.
The workaround to end the loop, we would have to call
std::set_new_handler(nullptr)
from within the handler itself, which gets complicated if the handler has to be
re-setted afterwards.
This patch adds the new_nothrow_no_retry configuration flag, which, if enabled,
will change the retrying behavior of operator new (std::nothrow) so that it
only calls
the handler once when it fails to allocate memory and the return nullptr.
The purpose of the loop is to give the new handler an opportunity
to free up enough memory to let the allocation succeed. Since the
handler doesn't get passed the size of the request it has no easy
way of determining how much memory to free. The loop lets it free
up increasingly more memory. If it can't free up any memory it is
expected/required to either indicate failure by throwing bad_alloc
or terminate the process. It's not allowed to return otherwise.
Besides violating the requirement of the C++ standard, replacing
the loop with an if statement would disable that aspect of the
feature for the whole system (or for all processes that link with
the libstdc++ that was configured this way). It would effectively
be imposing a system-wide policy without providing a mechanism
for correctly written programs to opt out. In addition, as
a configuration option, it could not be easily tested. I would
therefore advise against making such a change.
Martin