Just recently I switched the language of my project to use C++ from C. With C, I used malloc and after that I check if malloc was successful but with C++, I use \'new\' to a
In C++ there are 2 primary ways in which new allocates memory and each requires different error checking.
The standard new operator will throw a std::bad_alloc exception on failure and this can be handled like a normal exception
try {
char* c = new char[100];
} catch (std::bad_alloc&) {
// Handle error
}
Or alternative the nothrow version of new will simply return NULL on failure
char* c = new (std::nothrow) char[100];
if (!c) {
// Handle error
}
I'm curious though as to what you expect to do when the allocation fails? If there is no memory available to allocate your object, there's often very little which can be done in the process.