5

exit(3) says that stdio streams are flushed and closed. But nothing tells about C++-specific ofstream objects.

Does the standard guarantee that ofstream objects are also flushed and closed properly, or do I have to somehow propagate exit condition to main() and do a return there to destroy all automatic ofstreams?

Ruslan
  • 18,162
  • 8
  • 67
  • 136
  • not really - they are not necessarily destroyed properly http://stackoverflow.com/questions/7054685/are-destructors-run-when-calling-exit but this is linux so I wouldn't worry ;) – user3125280 Dec 26 '13 at 12:19

2 Answers2

6

std::exit() destroys objects with static storage duration (thereby flushing such ofstream objects). It does not destroy objects with automatic storage duration (leaving such ofstream objects unflushed).

Whether the ofstream is flushed depends on its storage duration.

Oswald
  • 31,254
  • 3
  • 43
  • 68
4

No, exit should not flush iostreams. iostreams are flushed on close() (on the stream types where it is available), when flush is called explicitly on the stream, or on destruction.

Using exit in your application will leave objects in the state they are in (unless they are static), so resources requiring cleanup will be leaked. This doesn't apply to memory leaks though, as most operating systems clean memory allocated for a program themselves, when the program exits.

This is one of the reasons that it is not recommended to call exit in your applications (unless in really exceptional cases) - you are better off throwing an exception than exit-ing.

Edit: By "really exceptional cases" I mean cases when you have strong requirements like "to avoid compromising the cryptographic key the library will call std::exit at this point, without allowing calling code to perform any other operations".

utnapistim
  • 26,809
  • 3
  • 46
  • 82
  • Throwing an exception looks like a good way of "propagating exit condition". – Ruslan Dec 26 '13 at 12:22
  • Yes, but it allows calling code to handle the error case without exiting the application. If your code calls `exit`, it's calling code has no chance to handle the error internally ( – utnapistim Dec 26 '13 at 12:27