Question

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?

Was it helpful?

Solution 2

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".

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top