How should I use FormatMessage() properly in C++?

后端 未结 8 828
悲&欢浪女
悲&欢浪女 2020-11-28 03:28

Without:

  • MFC
  • ATL

How can I use FormatMessage() to get the error text for a HRESULT?

 HRES         


        
8条回答
  •  旧巷少年郎
    2020-11-28 04:30

    Keep in mind that you cannot do the following:

    {
       LPCTSTR errorText = _com_error(hresult).ErrorMessage();
    
       // do something with the error...
    
       //automatic cleanup when error goes out of scope
    }
    

    As the class is created and destroyed on the stack leaving errorText to point to an invalid location. In most cases this location will still contain the error string, but that likelihood falls away fast when writing threaded applications.

    So always do it as follows as answered by Shog9 above:

    {
       _com_error error(hresult);
       LPCTSTR errorText = error.ErrorMessage();
    
       // do something with the error...
    
       //automatic cleanup when error goes out of scope
    }
    

提交回复
热议问题