Re: Simple question about exit(1)
On Jun 18, 11:05 am, Vicent Giner-Bosch <vgi...@gmail.com> wrote:
Hello.
If I do "exit(1)" in any part of my program, does it take into account
allocated space (instances of objects, and so on) and de-allocate it
before termining the execution??
Why do you want to exit like that? It's not needed and, to the
contrary of what some people said here, it's not very safe either.
On a full-fledged OS of today, like Windows/Unix, sure, all OS
resources will be freed, but what about e.g. your program data? E.g.
what if you started writing something to some file of yours and
terminated in the middle? If file OK? Will you be able to recover if
it's cut in a bad place?
In other words, you don't do exit(1) as a matter of fact, not in C,
not in C++.
Luckily, in C++, you can easily get what you want, which, I guess, is
to leave all your processing when something really catastrophic
happen. Here's what you can do:
In catastrophy.hpp
extern void catastrophy(int exit_code);
In catastrophy_impl.hpp
struct catastrophy_exception
{
catastrophy_exception(int exit_code): _exit_code(exit_code)
{
}
const int _exit_code;
};
In catastrophy_impl.cpp
void catastrophy(int exit_code)
{
throw catastrophy_exception(exit_code);
}
In main.cpp:
#include "catastrophy_impl.hpp"
int main(...)
{
try
{
workworkwork();
return 0;
}
catch(catastrophy_exception whoops)
{
return whoops._exit_code;
}
}
The above is a near-equivalent to exit(), but has a major advantage:
stack unwind happens. So as long as your code cleans-up properly in
case of exceptions (and that's what you should have anyhow), it's much
better.
In any other file, include catastrophy.hpp and call catastrophy() if
you need it. Don't ever try to catch catastrophy_exception, and don't
ever catch(...) without a rethrow. In fact, don't ever write
catch(...). Given exception handling tools we have today in C++,
catch(...) {} is a bug, even if it has a throw in it.
Given that you are asking in light of exceptions... You probably need
to learn how to write exception-safe code. That goes for C++ as well
as for any language that uses exceptions. That's tough, but
rewarding :-).
Note: in files where you don't include catastrophy_impl.hpp, you can't
catch catastrophy_exception, that just won't compile, obvoiusly. So
don't include it, include only catastrophy.hpp!
Goran.