For class specific new_handler implementation, i came across the following example in book “effective c++”. This looks problem in multithreaded environment, My Question is how to achieve class specific new_handler in multithreaded environment?
void * X::operator new(size_t size)
{
new_handler globalHandler = // install X's
std::set_new_handler(currentHandler); // handler
void *memory;
try { // attempt
memory = ::operator new(size); // allocation
}
catch (std::bad_alloc&) { // restore
std::set_new_handler(globalHandler); // handler;
throw; // propagate
} // exception
std::set_new_handler(globalHandler); // restore
// handler
return memory;
}
You’re right. This is probably not thread safe. You might want to consider an alternative approach like using the
nothrowversion ofnewinstead:This will cause your class-specific handler to be called whenever memory allocation fails. I wouldn’t do this until you really understand all of the headaches surrounding overloading
operator new. In particular, read Herb Sutter’s two part article To New, Perchance To Throw, Part 1 and Part 2. Interestingly enough, he says to avoid thenothrowversion… hmmm.