【问题标题】:Does CString preserve GetLastError code?CString 是否保留 GetLastError 代码?
【发布时间】:2014-07-20 23:17:12
【问题描述】:

我需要使用 MFC 的 CString 将一些调试信息发布到日志中,但我似乎无法找到它是否保留了最后一个 WinAPI 设置的错误代码(并且可以使用 GetLastError 检索)?

编辑:这是我目前在现有项目中所做的简化版本的代码示例:

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?
}

【问题讨论】:

  • CString 的方法不可能保留错误代码。一些方法进行 API 调用(通过newmalloc),如果他们有代码来保存错误代码,那将是非常令人惊讶的,因为这不是CString 会关心的事情。它处于错误的抽象级别。
  • 您可以将 GetLastError 代码保留在 DWORD 中。 CString 和它有什么关系?
  • 返回 CString 会调用复制构造函数,这可能会影响 GetLastError。 (例如,如果存在每个线程的CString 缓存,则对TlsGetValue 的调用将破坏GetLastError。)通常,不能保证任何函数在成功时保留GetLastError
  • 在示例中,您展示了将“最后一个错误”代码缓存在您自己的成员变量(或全局)中而不是尝试猜测使用 SetLastError 和 @ 是否安全987654335@.
  • 为什么不在调用时将GetLastError 的值传递给您的日志记录函数? GetLastError 只保证在返回失败的调用之后立即有意义,因此此时您应该保存错误代码。

标签: c++ string winapi mfc getlasterror


【解决方案1】:

一个方便的解决方案是定义一个包含 CString 和最后一个错误代码的类,然后重载 logError 并重新定义 collectDebuggerInfo 如下所示:

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);
}

这样您就不必更改调用错误处理函数的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2014-06-07
    相关资源
    最近更新 更多