MEM52-CPP. Detect and handle memory allocation errors
The default memory allocation operator, ::operator new(std::size_t) , throws a std::bad_alloc exception if the allocation fails. Therefore, you need not check whether calling ::operator new(std::size_t) results in nullptr . The nonthrowing form, ::operator new(std::size_t, const std::nothrow_t &) , does not throw an exception if the allocation fails but instead returns nullptr . The same behaviors apply for the operator new[] versions of both allocation functions. Additionally, the default allocator object ( std::allocator ) uses ::operator new(std::size_t) to perform allocations and should be treated similarly.
T *p1 = new T; // Throws std::bad_alloc if allocation fails
T *p2 = new (std::nothrow) T; // Returns nullptr if allocation fails
T *p3 = new T[1]; // Throws std::bad_alloc if the allocation fails
T *p4 = new (std::nothrow) T[1]; // Returns nullptr if the allocation fails
Furthermore, operator new[] can throw an error of type std::bad_array_