exit(0)是否会在MFC中造成任何问题?

Chr*_*son 2 c++ mfc

我想立即在C++中退出我的MFC应用程序.退出(0)是最佳解决方案吗?例如.它是否可以防止析构函数被调用,它是否是线程安全的?等有更好的解决方案吗?谢谢.

Ada*_*eld 6

是的,exit(0)是最好的解决方案.它将导致全局对象(和static函数内的对象)的析构函数运行,但是它不会导致堆栈分配或堆分配对象的析构函数运行:

// At global scope
ClassWithDestruct globalObject;

void SomeFunction()
{
    static ClassWithDestructor staticObject;
    ClassWithDestructor stackObject;
    ClassWithDestructor *heapObject = new ClassWithDestructor;

    // On the following call to exit(), the destructors of 'globalObject' and
    // 'staticObject' will run, but those of 'stackObject' and 'heapObject' will
    // NOT run
    exit(0);
}
Run Code Online (Sandbox Code Playgroud)

至于它是否是线程安全的,这是一个难以回答的问题:你不应该exit同时从多个线程调用,你应该只调用一次.如果任何析构函数由于exit或者atexit运行时注册的任何函数运行,那么显然这些函数应该是线程安全的,如果它们处理可能被其他线程使用的数据.

如果您的程序正常退出(例如,由于用户请求退出),您应该exitmain/ 调用或返回WinMain,这相当于调用exit.如果您的程序退出异常(比如,作为访问冲突或断言失败的结果),你应该叫无论是_exitabort,其中调用任何析构函数.