C++中,exit和return有什麼不同?

總能看到,但是你知道這兩者有什麼不同呢?

------------------------------------------------------------------------

exit() is used to exit the program as a whole. In other words it returns control to the operating system.Afterexit() all memory and temporary storage areas are all flushed out and control goes out of program.

In contrast, the return() statement is used to return from a function and return control to the calling function.

Also in a program there can be only one exit () statement but a function can have number of return statements. In other words there is no restriction on the number of return statements that can be present in a function.

------------------------------------------------------------------------



不知道這個不同會不會有問題?通常會,除非你不用他們。

最近review一個老代碼的CR時,碰到了一個跟它相關的問題。

void main()

{

   CRuntimeEnvInit a;

   //a bunch of logic here...

   exit(l_exitCode);

   return 0;

}

在vs2010上,這會有什麼問題?a的析構函數不會被調用。這似乎不要緊,如果有內存泄漏,這個時候也會被OS收回。但要命的是CRuntimeEnvInit 會初始化很多全局的東西,包括打開重要文件。這樣一來,這些文件總是被打開!!!

爲什麼會這樣?通過“go to disassembly”可以得知,析構函數時在return那裏,exit直接退出,導致了析構函數沒有被調用。


所以結論是什麼呢?

When I call returninmain(), destructors will be called for my locally scoped objects. If I callexit(),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.

選用這兩者之前,要想清楚。

還有一種方案,針對全局變量和main函數的local變量, 那就是register一個函數給atexit,並在這個函數中寫上release resource的代碼。然後不管何時exit,總能把resource release。


參考

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

http://stackoverflow.com/questions/461449/return-statement-vs-exit-in-main

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章