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 nothrow
version of new
instead:
void* X::operator new(std::size_t sz) {
void *p;
while ((p = ::operator new(sz, std::nothrow) == NULL) {
X::new_handler();
}
return p;
}
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 the nothrow
version... hmmm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With