Mega Code Archive

 
Categories / C++ / Language
 

Watch for allocation errors using both old-style and new-style error handling

#include <iostream> #include <new> using namespace std; class MyClass {   static int count; public:   MyClass() {       count++;    }   ~MyClass() {       count--;    }   int getcount() {       return count;    } }; int MyClass::count = 0;  int main() {   MyClass object1, object2, object3;   cout << object1.getcount() << " objects in existence\n";   MyClass *p;   try {     p = new MyClass;      if(!p) {        cout << "Allocation error\n";       return 1;     }   } catch(bad_alloc ba) {        cout << "Allocation error\n";       return 1;   }   cout << object1.getcount();   cout << " objects in existence after allocation\n";   delete p;   cout << object1.getcount();   cout << " objects in existence after deletion\n";   return 0; }