return语句vs exit()in main() [英] return statement vs exit() in main()

查看:178
本文介绍了return语句vs exit()in main()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该使用 exit()或只是 return / code>?我个人喜欢 return 语句,因为我觉得它像读取任何其他函数和流控制,当我阅读代码是平滑的(在我看来)。即使我想重构 main()函数, return 看起来像一个更好的选择比 exit()



return 不会?

解决方案

一个区别,但它是微妙的。



当我在<$ c $中调用 return c> main(),将为我的本地作用域对象调用析构函数。如果我调用 exit()将不会为我的本地作用域对象调用析构函数!重新读取。 exit() 不返回。这意味着,一旦我打电话,有没有后援。您在该函数中创建的任何对象都不会被销毁。通常这没有影响,但有时它会,像关闭文件(肯定你希望所有的数据刷新到磁盘。)



注意即使调用 exit(),静态对象也会被清除。最后注意,如果你使用 abort(),没有对象会被销毁。也就是说,没有全局对象,没有静态对象,也没有局部对象将被调用它们的析构函数。



> http://groups.google.com/group/gnu.gcc.help/msg/8348c50030cfd15a


Should I use exit() or just return statements in main()? Personally I favor the return statements because I feel it's like reading any other function and the flow control when I'm reading the code is smooth (in my opinion). And even if I want to refactor the main() function, having return seems like a better choice than exit().

Does exit() do anything special that return doesn't?

解决方案

Actually, there is a difference, but it's subtle. It has more implications for C++, but the differences are important.

When I call return in main(), destructors will be called for my locally scoped objects. If I call exit(), no destructor will be called for my locally scoped objects! Re-read that. exit() does not return. That means that once I call it, there are "no backsies." Any objects that you've created in that function will not be destroyed. Often this has no implications, but sometimes it does, like closing files (surely you want all your data flushed to disk?).

Note that static objects will be cleaned up even if you call exit(). Finally note, that if you use abort(), no objects will be destroyed. That is, no global objects, no static objects and no local objects will have their destructors called.

Proceed with caution when favoring exit over return.

http://groups.google.com/group/gnu.gcc.help/msg/8348c50030cfd15a

这篇关于return语句vs exit()in main()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆