Does CString preserve GetLastError code?

孤人 提交于 2019-12-13 08:38:49

问题


I need to post some debugging information into a log using MFC's CString, but I can't seem to find if it preserves error code set by the last WinAPI (and retrievable with GetLastError)?

EDIT: Here's a code example of a simplified version of what I'm currently doing in my existing project:

HANDLE hFile = CreateFile(strFilePath, ...);
if(hFile == INVALID_HANDLE_VALUE)
{
    logError(collectDebuggerInfo(strFilePath));
}

void logError(LPCTSTR pStrDesc)
{
    int nLastError = ::GetLastError();
    CString str;
    str.Format(L"LastError=%d, Description: %s", nLastError, pStrDesc);

    //Add 'str' to the logging file...
}

CString collectDebuggerInfo(LPCTSTR pFilePath)
{
    int nLastError = ::GetLastError();
    CString str;

    str.Format(L"Debugging info for file: \"%s\"", pFilePath);

    ::SetLastError(nLastError);
    return str;   //RETURNING CString -- will it overwrite the last error?
}

回答1:


One convenient solution would be to define a class that contains both a CString and a last error code, then overload logError and redefine collectDebuggerInfo something like this:

void logError(StringWithEmbeddedErrorCode instr)
{
    LPCTSTR pStrDesc = instr.str;
    SetLastError(instr.nLastError);
    logError(pStrDesc);
}

StringWithEmbeddedErrorCode collectDebuggerInfo(LPCTSTR pFilePath)
{
    int nLastError = ::GetLastError();
    CString str;

    str.Format(L"Debugging info for file: \"%s\"", pFilePath);

    return StringWithEmbeddedErrorCode(str, nLastError);
}

This way you don't have to change the code that invokes the error handling functions.



来源:https://stackoverflow.com/questions/24855841/does-cstring-preserve-getlasterror-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!