My bad memory at work again.Bo Persson wrote: ↑Fri Dec 30, 2022 7:35 pmnew does not return at all on failure, but throws a bad_alloc exception. So this case never happens.Mike Sherwin wrote: ↑Fri Dec 30, 2022 4:22 amCode: Select all
if (thread[i] == nullptr) { // new returns nullptr on allocation failure.
However; it can return a nullptr which is what I forgot to tell it.
By default, one of the versions of operator new is overloaded to accept a parameter of type nothrow_t (like nothrow). The value itself is not used, but that version of operator new shall return a null pointer in case of failure instead of throwing an exception.
The same applies to the new[] operator and function operator new[].
Example:
// nothrow example
#include <iostream> // std::cout
#include <new> // std::nothrow
int main () {
std::cout << "Attempting to allocate 1 MiB... ";
char* p = new (std::nothrow) char [1048576];
if (!p) { // null pointers are implicitly converted to false
std::cout << "Failed!\n";
}
else {
std::cout << "Succeeded!\n";
delete[] p;
}
return 0;
}