#include #include #include #include struct Foo { Foo() { std::cout << "Foo::Foo" << std::endl; // hack it so the constructor will throw an exception on the 2nd iteration static int counter = 1; if (counter++ == 2) { throw 1; } } ~Foo() { std::cout << "Foo::~Foo" << std::endl; } static void* operator new (size_t size) { std::cout << "Foo::operator new called\n"; // hack so we run out of memory after 5 iterations static int counter = 1; if (counter++ > 5) { throw std::bad_alloc(); } void *p = malloc(size); if (p==0) { throw std::bad_alloc(); } return p; } static void operator delete (void *p) { std::cout << "Foo::operator delete called\n"; free(p); } int x; }; int main(int argc, char** argv) { Foo* fp; for (int i = 0 ; i < 8; 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; } std::cout << "Call global new and make sure it does not call our version of operator new and delete" << std::endl; int* ip = new int; delete ip; return 0; }