-
Notifications
You must be signed in to change notification settings - Fork 240
Last error preservation
Raymond Chen edited this page Aug 24, 2020
·
1 revision
The wil::last_error_context
class is defined in wil/resource.h
as part of the RAII resource wrappers library.
It captures the value of GetLastError
when it is constructed and restores it when it is destructed.
This is useful in library code that runs during a value's destructor. If
the library code could inadvertently change the value of GetLastError
(by calling a Win32 API or similar), it should instantiate a value of
this type before calling the library function in order to preserve the
GetLastError
value the user would expect.
In kernel mode, this class does nothing, but the class remains defined so that the wil library is insulated from differences between kernel mode and user mode.
- Constructor:
last_error_context()
takes no parameters. - Move-assignable and move-copyable. Any obligation to restore the error code is transferred to the moved-to object.
- The
release
method removes the obligation to restore the error code.
void LogMessage(...)
{
// Logging a message should not change GetLastError.
auto preserveLastError = wil::last_error_context();
// The logging code might allocate memory or write to files,
// and those calls may change GetLastError. But that's okay,
// because the preserveLastError will restore the error code
// for us.
... logging code...
}