Construct std::error_code from errno on POSIX and GetLastError() on Windows

后端 未结 2 1441
猫巷女王i
猫巷女王i 2021-02-05 04:35

My question: What is the correct way to construct std::error_code instances from errno values on POSIX and GetLastError() on Windows so th

相关标签:
2条回答
  • 2021-02-05 04:54

    This is an old question, but I haven't really found a good answer on SO. The accepted answer confuses me a little as it seems to give an error_condition rather than an error_code. I have settled on the following for myself on POSIX:

    std::error_code error_code_from_errno(int errno_code) {
      return std::make_error_code(static_cast<std::errc>(errno_code));
    }
    

    This always gives me the correct category (generic or system). I've had problems in the past where error codes with the same errno code compared as not equal because one had generic_category and the other had system_category.

    0 讨论(0)
  • 2021-02-05 05:04

    That's a quality of implementation issue. The const static object returned by std::system_category() is relied upon to perform the mapping from the platform-native error code enumeration to the standard std::error_condition enumeration. Under 17.6.5.14 Value of error codes [value.error.codes]:

    Implementations for operating systems that are not based on POSIX are encouraged to define values identical to the operating system’s values.

    You can see in http://www.boost.org/doc/libs/1_46_1/libs/system/src/error_code.cpp how Boost performs the mapping; any standard library supplied by your compiler vendor for use on Windows should do something similar.

    The intended behaviour is covered in 19.5.1.5p4, describing system_category().default_error_condition(int ev):

    If the argument ev corresponds to a POSIX errno value posv, the function shall return error_condition(posv, generic_category()). Otherwise, the function shall return error_condition(ev, system_category()).

    So, for example, error_code(ERROR_FILE_NOT_FOUND, std::system_category()).default_error_condition() will invoke std::system_category().default_error_condition(ERROR_FILE_NOT_FOUND), which should return std::error_condition(std::no_such_file_or_directory, std::generic_category()).

    0 讨论(0)
提交回复
热议问题