#include #include #include #include struct Foo { // hack it so the constructor will throw an exception on the 2nd iteration Foo() { std::cout << "Foo::Foo" << std::endl; static int count = 1; if ( count++ == 2 ) { throw count; } } ~Foo() { std::cout << "Foo::~Foo" << std::endl; } int x; }; // overriding the global operator new function void* operator new (size_t size) throw(std::bad_alloc) { std::cout << "my allocation function called\n"; // hack it so it appears there is no memory after 4 iterations static int count = 1; if ( count++ > 4 ) { throw std::bad_alloc(); } void *p = malloc(size); if (p==0) { throw std::bad_alloc(); } return p; } // overriding the global operator delete function void operator delete (void *p) throw() { std::cout << "my deallocation function called\n"; free(p); } int main(int argc, char** argv) { Foo* fp; for (int i = 0 ; i < 7; i++) { std::cout << "=======================================================" << std::endl; try { fp = new Foo; fp->x = i; std::cout << fp->x << std::endl; delete fp; } catch(std::bad_alloc e) { std::cout << "caught bad_alloc exception" << std::endl; } catch(int x) { std::cout << "constructor threw" << std::endl; } std::cout << "=======================================================" << std::endl; } return 0; }