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

本文详细解析了C++中exit()和return()函数的区别和使用场景,特别关注了它们对析构函数的影响以及如何避免相关问题。通过实例分析,阐述了不当使用可能导致的内存泄漏风险,强调了正确选择使用时机的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总能看到,但是你知道这两者有什么不同呢?

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值