C
changzhouwang
Hi all:
I need to handle std::bad_alloc exceptions (thrown by new due to out-
of-memory) in two different ways for two cases. For the majority case,
I need to print a log message and abort the process. For some special
case, I can free some memory and retry the new statement.
Instead of catching all the std::bad_alloc exceptions for each new
operation, I would like to use global function set_new_handler. Since
the handler does not have any parameter and will not be aware of which
case I am in, I need to switch the handler before the new operation
for the special case and switch it back (this will make most of my new
operations unchanged for the majority case). For example, I can
override the class specific operator new so that it change the handler
before and after calling the global new operator. This is indeed
suggested by item 7 in the Effective C++ (second edition) book by
Scott Meyers.
My problem is: how do I make sure that the new operations for the
major case are not executed when I switch the handler?
If the operator new is executed as an atomic block (i.e., when any
operator new is running in any thread T, no other thread can run this
or other operator new before T finished the call of operator new),
this issue does not exist and I am happy.
Otherwise, I can use a mutex in the overriden operator new in the
special cases. However, how do I prevent other operator new been
called when the mutex is locked.
Thanks,
czw
I need to handle std::bad_alloc exceptions (thrown by new due to out-
of-memory) in two different ways for two cases. For the majority case,
I need to print a log message and abort the process. For some special
case, I can free some memory and retry the new statement.
Instead of catching all the std::bad_alloc exceptions for each new
operation, I would like to use global function set_new_handler. Since
the handler does not have any parameter and will not be aware of which
case I am in, I need to switch the handler before the new operation
for the special case and switch it back (this will make most of my new
operations unchanged for the majority case). For example, I can
override the class specific operator new so that it change the handler
before and after calling the global new operator. This is indeed
suggested by item 7 in the Effective C++ (second edition) book by
Scott Meyers.
My problem is: how do I make sure that the new operations for the
major case are not executed when I switch the handler?
If the operator new is executed as an atomic block (i.e., when any
operator new is running in any thread T, no other thread can run this
or other operator new before T finished the call of operator new),
this issue does not exist and I am happy.
Otherwise, I can use a mutex in the overriden operator new in the
special cases. However, how do I prevent other operator new been
called when the mutex is locked.
Thanks,
czw