Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

前端 未结 16 1387
情深已故
情深已故 2020-11-22 17:15

Does C++ support \'finally\' blocks?

What is the RAII idiom?

What is the difference between C++\'s RAII idiom and C#\'s \'using\' statement?

16条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 17:37

    FWIW, Microsoft Visual C++ does support try,finally and it has historically been used in MFC apps as a method of catching serious exceptions that would otherwise result in a crash. For example;

    int CMyApp::Run() 
    {
        __try
        {
            int i = CWinApp::Run();
            m_Exitok = MAGIC_EXIT_NO;
            return i;
        }
        __finally
        {
            if (m_Exitok != MAGIC_EXIT_NO)
                FaultHandler();
        }
    }
    

    I've used this in the past to do things like save backups of open files prior to exit. Certain JIT debugging settings will break this mechanism though.

提交回复
热议问题