Best way to safely name a new one in this trivial example?

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 successfully
  • nest 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?

+6
source share
2 answers

You can do it

  • Announce them first. Set to nullptr
  • Run the try block
  • To distribute.
  • Catch - delete them - delete nullprt - this is noop
+6
source

I think you could write a long program as shown below (but I don't know if it would be 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; } 
0
source

Source: https://habr.com/ru/post/984106/


All Articles