exit(0) 在 MFC 中会造成任何问题吗?
我想立即退出 C++ 中的 MFC 应用程序。 exit(0) 是最好的解决方案吗?例如。它是否阻止析构函数被调用,它是线程安全的吗?等等,有更好的解决方案吗?谢谢。
I want to immediately exit my MFC app in C++. Is exit(0) the best solution? eg. does it prevent destructors from being called, is it threadsafe? etc. Is there a better solution? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,
exit(0)
是最好的解决方案。它将导致全局对象(以及函数内的静态对象)的析构函数运行,但不会导致堆栈分配或堆分配对象的析构函数运行:至于它是否是线程-安全,这是一个很难回答的问题:您不应该从多个线程同时调用
exit
,您应该只调用它一次。如果任何析构函数由于exit
而运行,或者任何使用atexit
运行,那么显然,如果这些函数处理可能被其他线程使用的数据,那么它们应该是线程安全的。如果您的程序正常退出(例如,由于用户请求退出),您应该调用
exit
或从main
/WinMain
返回code>,相当于调用exit
。如果您的程序异常退出(例如,由于访问冲突或断言失败),您应该调用_exit
或abort
,其中不调用任何析构函数。Yes,
exit(0)
is the best solution. It will cause the destructors of global objects (andstatic
objects within functions) to run, however it will not cause destructors of stack-allocated or heap-allocated objects to run:As to whether or not it's thread-safe, that's a hard question to answer: you should not be calling
exit
simultaneously from multiple threads, you should only call it once. If any destructors run as a result ofexit
, or any if any functions registered withatexit
run, then obviously those functions should be thread-safe if they deal with data that could potentially be being used by other threads.If your program is exiting normally (say, as a result of the user requesting an exit), you should either call
exit
or return frommain
/WinMain
, which is equivalent to callingexit
. If your program is exiting abnormally (say, as a result of an access violation or failed assertion), you should call either_exit
orabort
, which do not call any destructors.如果您想立即退出,并确保事先不运行任何析构函数等,那么您可能需要调用
abort()
。如果您确实希望执行析构函数,那么您可能需要使用PostQuitMessage(0);
。不管怎样,exit()
可能是错误的选择。If you want to exit immediately, ensuring against running any destructors and such beforehand, then you probably want to call
abort()
. If you do want destructors to execute, then you probably want to usePostQuitMessage(0);
. Either way,exit()
is probably the wrong choice.当 win32 进程退出时,操作系统会清除与其关联的任何资源,所以对我来说这是完全可以的。
when a win32 process exits any resource associated with it is cleaned up by the OS, so in order to me it is perfectly ok.
exit(0) 退出进程。所有内存都被清理干净。另一方面,显式管理的资源可能不会被关闭。当然,文件句柄将被关闭,Windows 缓冲区中的内容将被刷新。但是应用程序管理的内容不会。
exit(0) exits the process. All memory is cleaned up. On the other hand explicitly managed resources may not be closed. Of course file handles would be closed and stuff in windows buffers will be flushed. However stuff that the application manages will not.
不,这不是结束程序的安全方法。静态存储数据和非本地自动对象将被破坏,但本地自动对象不会。
从 C++ 标准 18.3/8 开始:
与此相关的是,
std::exit(EXIT_SUCCESS)
具有令人不安的误导性。No, it's not a safe way to end your program. Static-storage data and non-local automatic objects will destruct, but local automatic objects will not.
From 18.3/8 in the C++ standard:
On a related note,
std::exit(EXIT_SUCCESS)
is disturbingly misleading.