在C++中,exit(0)和return(0)有什么区别?
当使用exit(0)退出程序时,不会调用本地范围的非静态对象的析构函数。但如果使用了返回值0,则会调用析构函数。
Program 1 – – uses exit(0) to exit
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Test {
public:
Test() {
printf("Inside Test's Constructor\n");
}
~Test(){
printf("Inside Test's Destructor");
getchar();
}
};
int main() {
Test t1;
// using exit(0) to exit from main
exit(0);
}
Output:
Inside Test’s Constructor
Program 2 – uses return 0 to exit
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Test {
public:
Test() {
printf("Inside Test's Constructor\n");
}
~Test(){
printf("Inside Test's Destructor");
}
};
int main() {
Test t1;
// using return 0 to exit from main
return 0;
}
Output:
Inside Test’s Constructor
Inside Test’s Destructor
调用析构函数有时很重要,例如,如果析构函数具有释放资源(如关闭文件)的代码。
请注意,即使我们调用exit(),静态对象也会被清理。例如,请参阅以下程序。
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Test {
public:
Test() {
printf("Inside Test's Constructor\n");
}
~Test(){
printf("Inside Test's Destructor");
getchar();
}
};
int main() {
static Test t1; // Note that t1 is static
exit(0);
}
Output:
Inside Test’s Constructor
Inside Test’s Destructor
>> 本文固定链接: http://www.vcgood.com/archives/4821