main()中的return语句vs exit()

在C++中,有什么区别? 出口(0) 返回0 ?

null

什么时候 出口(0) 用于退出程序,则不调用局部作用域非静态对象的析构函数。但如果使用返回0,则会调用析构函数。

程序1–使用退出(0)退出

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Test {
public :
Test() {
printf ( "Inside Test's Constructor" );
}
~Test(){
printf ( "Inside Test's Destructor" );
getchar ();
}
};
int main() {
Test t1;
// using exit(0) to exit from main
exit (0);
}


输出: 内部测试的构造函数

程序2–使用返回0退出

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Test {
public :
Test() {
printf ( "Inside Test's Constructor" );
}
~Test(){
printf ( "Inside Test's Destructor" );
}
};
int main() {
Test t1;
// using return 0 to exit from main
return 0;
}


输出: 内部测试的构造函数 内部测试的析构函数

调用析构函数有时很重要,例如,如果析构函数有代码来释放资源,比如关闭文件。

请注意,即使调用exit(),静态对象也会被清除。例如,请参阅下面的程序。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Test {
public :
Test() {
printf ( "Inside Test's Constructor" );
}
~Test(){
printf ( "Inside Test's Destructor" );
getchar ();
}
};
int main() {
static Test t1; // Note that t1 is static
exit (0);
}


输出: 内部测试的构造函数 内部测试的析构函数

贡献者 indiarox 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享