#include <iostream> <!--more--> #include <exception> using namespace std;
class newBad { static int i; static void *p;
public: void *operator new(size_t sz) { p = ::operator new(sz); cout << "The newBad object number: " << i + 1 << " has been created" << endl; if (++i >= 11) { throw out_of_range("the 11st object created failed."); } return p; }
static void releaseMemory() { if (p) { ::operator delete(p); cout << "the " << i << "st object was freed" << endl; i--; } } };
int newBad::i = 0; void *newBad::p = nullptr;
int main(int argc, char const *argv[]) { while (true) { try { newBad *mp = new newBad; } catch (const std::exception &e) { std::cerr << e.what() << '\n'; newBad::releaseMemory(); } } return 0; }
|