问题
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