-
Help with destructor
In the following program
Code:
#include<iostream>
using namespace std;
void MyExit(void)
{
cout<<endl<<"Exit from function!"<<endl;
exit(0);
}
class MyClass
{
public:
MyClass(void)
{
cout<<endl<<"Object initialized!";
}
~MyClass()
{
cout<<endl<<"Object destoryed!"<<endl;
}
};
int main()
{
MyClass C1;
MyExit();
return 0;
}
The destructor is not executing. What is the reason?
Although I am not terminating the program in main() but still on termination C! should go out of scope which means that the dertructor should run. But it is not happening. Why?
-
You're terminating the program before the variable's scope ends. The scope lasts until main returns.
If you wanted it to be destroyed earlier then you'd need to insert an additional scope:
Code:
int main()
{
{
MyClass C1;
}
MyExit();
return 0;
}
-
To be more specific, calling exit() "terminates the program without leaving the current block and hence without destroying objects of automatic storage duration" (that is a direct quote from the C++ standard, Section 3.6.1, para 4). C1 is an object of automatic storage duration. For struct/class types, the destructor is invoked during the process of destroying an object.
-
Avoid using exit. In C, it might be justified, but in C++, as you see, it can cause all sorts of problems.
Always let main go out of scope.
-
Well if I want to run destructor at every point I terminate the program. What should I do. I may be using this exit() at more than one point.
-
Don't use exit. Use exceptions instead to signal an error and (possibly) catch it in main.
-
Well I will post my actual program were I need to do this.
-
-
Read Elysia's last post again. Apart the advice not to call exit(), there is also a suggestion of what you can do instead. No need to post code where you consider you need to call exit().