My question: What is the correct way to construct std::error_code
instances from errno
values on POSIX and GetLastError()
on Windows so that the instances can be compared to the well-known values from std::errc
?
The longer explanation: My goal is to add an std::error_code
instance to a self-made exception object that works on POSIX and Windows systems in a C++11ish way.
In my cross-platform application I'm using a self-made I/O class hierarchy that uses the POSIX fopen()
and Windows' CreateFile()
calls for opening/creating files. If that fails a generic, self-made open_error
exception is thrown (it is derived from std::exception
, yes, but it's not one of C++'s predefined exception classes). I'm trying to extend this rather bare-bones exception with an error code; to be more precise with C++11's std::error_code
if I understood correctly.
My problem is how to construct such an object from errno
(in the POSIX case) or GetLastError()
(in the Windows case). For POSIX, as far as I've understood things, I can simply use errno
in std::error_code
's constructor, e.g. like this:
std::error_code ec(errno, std::generic_category());
And that ec
should be comparable to the well-known values from std::errc
.
For Windows a similar call can be made, of course:
std::error_code ec(::GetLastError(), std::generic_category());
But I'm not sure whether or not the values returned by GetLastError()
map nicely to the well-known constants from std::errc
. I've read in Boost's system library that they do for Boost's implementation of error_code
, but I'm asking about the std
implementation, not about Boost's.
Please don't advice to switch to using C++ streams for file access. I'd love to, but refactoring half of my code is not something I'd like to do right at this very moment.