总能看到,但是你知道这两者有什么不同呢?
------------------------------------------------------------------------
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