Re: overloading new/delete ....
Here is the code:
I am using visual studio 2005.
class ExceptionRouter{
public:
ExceptionRouter(){ std::cout<<"ExceptionRouter ctor
called"<<std::endl;};
~ExceptionRouter(){std::cout<<"ExceptionRouter dtor
called"<<std::endl; counter=0;};
// I want to choose what exception to throw at run time .. I do not
know how
// please help. This method is to demo other type of exception
later on
void throwException(exception& e, std::string &s)){
std::cout<<s<<std::endl;
throw (e);
++counter;
};
private:
static int counter; // count the total number of exception thrown
};
static int MyAlloc::counter=0;
class MyMemoryHandler
{
public:
static void* operator new(size_t size) { return ::operator
new(size);};
static void* operator new(size_t,ExceptionRouter& m)
{
std::cout << "new throwing bad_alloc" << std::endl;
m.throwException(std::bad_alloc,"bad_alloc is thrown");
} ;
static void* operator new[](size_t size) {return ::operator
new[](size);};
static void* operator new[](size_t size, ExceptionRouter& m) {
std::cout << "new throwing bad_alloc" << std::endl;
m.throwException(std::bad_alloc,"bad_alloc is thrown");
};
// Please help, the following are the only signature I can use
to make the program compiles.. But I want delete to throw..
static void operator delete(void* p,const std::nothrow_t)throw();
static void operator delete(void* p,const
std::nothrow_t,ExceptionRouter& m)throw();
static void operator delete[](void* p,const std::nothrow_t)throw();
static void operator delete[](void* p,const
std::nothrow_t,ExceptionRouter& m)throw();
private:
int mode;
MyMemoryHandler(void);
~MyMemoryHandler(void);
};
Sample main program:
int main(){
ExceptionRouter e;
char* array1 = new char[10]; // not throw
char *array2 = new(char[10], e); //throw .. don't know how to do
this.
}
The ultimate client file is just an ordinary template version of a
Stack class.
mlimber wrote:
learning wrote:
hi I am trying to make some simple app to learn exception safety
coding. I know that new and delete can throw bad_alloc but how can I
force them to throw by a flag "change" at run time?
I am overloading new, new[], delete and delete[], change is set to 1
then it calls the custom operators. If 0, it calls the c++. But how can
I overload delete and delete[]?
The original library signature has const std::nothrow_ and throw()
If I overload this, I need to have the same signature. But I want
delete to throw, so taht I can controal what and how destructor throw.
New is I have problem in thinking of how to overload delete[].
I am a bit stale in C++, so more detailed comments are very welcome.
Post a minimal but complete sample and we'll see what we can do to
help.
Cheers! --M