For a school project, I have 3 classes: egg, nest and chicken. We need to use new to instantiate each in main , call display() for each, and then explicitly delete each. It is easy.
My problem is not how to catch bad_alloc ; must be thrown on any of the new calls.
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 about packing the whole block from the first new to the last delete in the try block, and then I just caught bad_alloc and called delete for each instance, but then I thought of the following scenario:
egg created successfullynest fails and issues a bad_alloc
If I call delete on all 3 at this point, hen should throw another exception, because it never stood out in the first place, so it cannot be free.
I know very well that you would not use new in an open form like this, but what is the best way to deal with this situation? Is it too trivial and artificial for proper handling?
source share