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 creatednest
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?
You can do this
nullptr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With