I have the following program where i am calling exit() in the destructor. When i create an object of type sample inside main() destructor is called once and program exits normally. But when i create a global object of type sample, “Destructing..” gets printed infinitely. Can anyone please explain how?
#include "iostream"
#include "conio.h"
using namespace std;
class sample
{
public:
~sample() {
cout <<"Destructing.."<<endl;
exit(0);
}
};
sample obj;
int main()
{
getch();
}
What’s happening is, the
exit()function is getting the program to call destructors on all of the global objects. And since at the point where your class’s destructor callsexit(1);the object is not yet considered to be destructed, the destructor gets called again, resulting in an infinite loop.You could get away with this:
But having a destructor call
exit()is a Bad Idea. consider one of these alternatives:main()abort()instead ofexit()(Thanks goldilocks for mentioning this one).abort()bypasses all of the cleaning up that is normally done whenexit()is called and whenmain()returns. However this is not necessarily a good idea either, as certain cleanup operations in your program could be quite critical.abort()is meant only for errors that are already so bad that bypassing cleanup is warranted.I suggested exceptions before but remembered about throwing exceptions from inside destructors and changed my mind. here’s why.
Note also, the behavior is not consistent – some compilers/environments result in an infinite loop, some don’t. It comes down to at which point in the destructor the object is considered to be destroyed. I would guess the standard either doesn’t cover this or says the behavior in this case is undefined.