Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to safely call new on this trivial example?

Tags:

c++

bad-alloc

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:

  • egg is successfully created
  • nest fails, and throws a bad_alloc

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?

like image 939
Carcigenicate Avatar asked Mar 22 '15 16:03

Carcigenicate


1 Answers

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
like image 145
Ed Heal Avatar answered Sep 19 '22 03:09

Ed Heal