Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using class specific set_new_handler

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;
}
like image 414
Learner Avatar asked Aug 26 '09 02:08

Learner


1 Answers

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.

like image 143
D.Shawley Avatar answered Sep 20 '22 17:09

D.Shawley