main() 中的 return 语句与 exit()
我应该在 main()
中使用 exit()
还是只使用 return
语句?我个人喜欢 return
语句,因为我觉得它就像阅读任何其他函数一样,并且当我阅读代码时流控制很流畅(在我看来).即使我想重构 main()
函数,使用 return
似乎比 exit()
更好.
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()
.
exit()
会做任何 return
不会做的特殊事情吗?
Does exit()
do anything special that return
doesn't?
推荐答案
其实是有的,但是很微妙.它对 C++ 的影响更大,但差异很重要.
Actually, there is a difference, but it's subtle. It has more implications for C++, but the differences are important.
当我在 main()
中调用 return
时,将为我的本地作用域对象调用析构函数.如果我调用 exit()
,将不会为我的本地范围对象调用任何析构函数!重新阅读.exit()
不返回.这意味着,一旦我称它为,就没有后盾".您在该函数中创建的任何对象都不会被销毁.通常这没有任何影响,但有时确实如此,例如关闭文件(您确定要将所有数据刷新到磁盘吗?).
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?).
请注意,即使您调用 exit()
,static
对象也会被清除.最后请注意,如果您使用 abort()
,则不会销毁任何对象.也就是说,不会调用全局对象、静态对象和局部对象的析构函数.
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.
选择退出而不是返回时要谨慎行事.
http://groups.google.com/group/gnu.gcc.help/msg/8348c50030cfd15a
相关文章