Minimal example:
#include <Windows.h>
#include <string>
int main(int /*argc*/, char* /*argv*/[]) {
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); //Behavior the same, with or without.
DWORD err = GetLastError();
std::string str;
return (int)err; //returns 127 iff line above uncommented, 0 iff commented
}
This program returns 127
, which corresponds to ERROR_PROC_NOT_FOUND
("The specified procedure could not be found."). Notice that err
is set before the std::string
is created. The program is compiled in debug mode with MSVC 2017.
Is this behavior expected? If not, can I get some confirmations (then, I'll file a bug report)?
GetLastError()
returns the last error code to be set by a WinAPI function called by this thread. Note that WinAPI functions do not necessarily set a code when they succeed:
Most functions call SetLastError or SetLastErrorEx only when they fail.
You haven't called a WinAPI function that failed. As such, the error code is indeterminate. It's either uninitialized (meaning undefined behavior) or set by an unknown function (only slightly less meaningless). The standard library uses exceptions to signal errors, not the Windows API.
"Is this behavior expected?"
The behavior is expected in the sense that any value would be acceptable since the function is not being used in the proper context.