在 C++ 中, exit(0)和return 0有什么区别?
当exit(0)用于退出程序时,不会调用局部范围的非静态对象的析构函数。但是如果使用 return 0,则调用析构函数。
程序1————使用exit(0)退出
输出:
Inside Test’s Constructor
程序 2 – 使用 return 0 退出
输出:
Inside Test’s Constructor
Inside Test’s Destructor
调用析构函数有时很重要,例如,如果析构函数具有释放资源(如关闭文件)的代码。
请注意,即使我们调用 exit(),静态对象也会被清除。例如,请参阅以下程序。
输出:
Inside Test’s Constructor
Inside Test’s Destructor
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Test {
public:
Test() {
printf("Inside Test's Constructorn");
}
~Test(){
printf("Inside Test's Destructor");
getchar();
}
};
int main() {
Test t1;
// using exit(0) to exit from main
exit(0);
}
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Test {
public:
Test() {
printf("Inside Test's Constructorn");
}
~Test(){
printf("Inside Test's Destructor");
}
};
int main() {
Test t1;
// using return 0 to exit from main
return 0;
}
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Test {
public:
Test() {
printf("Inside Test's Constructorn");
}
~Test(){
printf("Inside Test's Destructor");
getchar();
}
};
int main() {
static Test t1; // Note that t1 is static
exit(0);
}