Why is std::string constructor resetting GetLastError

前端 未结 3 1511
走了就别回头了
走了就别回头了 2021-01-13 17:26

I\'m calling Windows APIs from C++ code and I have a helper method to do the FormatMessage stuff and throw an exception for error handling. The signature of the

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-13 18:00

    Per the documentation for GetLastError

    The Return Value section of the documentation for each function that sets the last-error code notes the conditions under which the function sets the last-error code. Most functions that set the thread's last-error code set it when they fail. However, some functions also set the last-error code when they succeed. If the function is not documented to set the last-error code, the value returned by this function is simply the most recent last-error code to have been set; some functions set the last-error code to 0 on success and others do not.

    At some point during the construction of std::string, SetLastError is called. The standard library on windows uses Win32 calls as part of its implementation.

    Your second method (that works) is the correct way to use GetLastError

    You should call the GetLastError function immediately when a function's return value indicates that such a call will return useful data. That is because some functions call SetLastError with a zero when they succeed, wiping out the error code set by the most recently failed function.

提交回复
热议问题