Watch for allocation errors using both old-style and new-style error handling. : New « Language « C++






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;
}


           
       








Related examples in the same category

1.Use new to allocate memory for primitive typeUse new to allocate memory for primitive type
2.Use new to allocate memory for a class and check errorUse new to allocate memory for a class and check error
3.Pointer for double and use new to allocate memoryPointer for double and use new to allocate memory
4.Demonstrate the new(nothrow) alternative.Demonstrate the new(nothrow) alternative.
5.Handle exceptions thrown by new.Handle exceptions thrown by new.
6.Force an allocation failure.Force an allocation failure.
7.Dynamic int arrayDynamic int array