Carcigenicate
Carcigenicate

Reputation: 45806

Best way to safely call new on this trivial example?

For a school project, I have 3 classes: an Egg, a Nest, and a Hen. We need to use new to create an instance of each in main, call display() on each, then explicitly delete each. That's all easy.

My problem is not knowing how to properly catch a bad_alloc; should 1 be thrown on any of the new calls.

Right now, it looks like this:

int main(int argc, char* argv[]) {
    using namespace std;

    cout << "Creating new instances on the heap..." << endl;
    Egg* egg = new Egg("New Egg");
    Nest* nest = new Nest("New Nest");
    Hen* hen = new Hen("New Hen");

    cout << sizeof(*egg) << endl;
    cout << sizeof(*nest) << endl;
    cout << sizeof(*hen) << endl;


    cout << "\nCalling display() on each..." << endl;
    egg->display();
    nest->display();
    hen->display();

    cout << "\nExplicitly deleting each instance..." << endl;
    delete egg;
    delete nest;
    delete hen;


    cout << "\nDone" << endl;

}

I thought of wrapping the entire block from the first new to the last delete in a try block, then just catching a bad_alloc, and calling delete on each instance, but then I thought of the following scenario:

If I call delete on all 3 at this point, hen should throw another exception because it was never allocated in the first place, so it can't be free'd.

I know ideally, you wouldn't use new out in the open like this, but what's the best way to handle this situation? Is it too trivial and artificial to be properly handled?

Upvotes: 6

Views: 111

Answers (2)

JoshOvi
JoshOvi

Reputation: 88

I guess you could write a long program like the following (but I do not know if it is necessarily better)

int main(int argc, char* argv[]) {
  using namespace std;
  Egg* egg;
  Nest* nest;
  Hen* hen;

  cout << "Creating new instances on the heap..." << endl;
  try {
    egg = new Egg("New Egg");
  } catch (std::bad_alloc& ba) {
     std::cerr << "bad_alloc caught: " << ba.what() << '\n';
     return 1;
  }

 try {
    nest = new Nest("New Nest");
  } catch (std::bad_alloc& ba) {
     std::cerr << "bad_alloc caught: " << ba.what() << '\n';
     delete egg;
     return 1;
  } 

  try {
    hen = new Hen("New Hen");
  } catch (std::bad_alloc& ba) {
     std::cerr << "bad_alloc caught: " << ba.what() << '\n';
     delete egg;
     delete nest;
     return 1;
  }

  cout << sizeof(*egg) << endl;
  cout << sizeof(*nest) << endl;
  cout << sizeof(*hen) << endl;


  cout << "\nCalling display() on each..." << endl;
  egg->display();
  nest->display();
  hen->display();

  cout << "\nExplicitly deleting each instance..." << endl;
  delete egg;
  delete nest;
  delete hen;


  cout << "\nDone" << endl;
  return 0;
}

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 60017

You can do this

  1. Declare them first. Set to nullptr
  2. Start the try block
  3. Allocate.
  4. Catch - delete them - delete nullprt is a noop

Upvotes: 6

Related Questions