error_code vs errno

tsh*_*h06 5 c++ error-handling errno c++11

我正在学习C++ 11标准.我想了解error_code和errno是否相互关联?如果是,那怎么样?如果没有那么我应该在哪些条件下设置errno以及在哪些条件下设置error_code?

我做了一个小测试程序来理解这一点,但仍然有点困惑.请帮忙.

#include <iostream>
#include <system_error>
#include <thread>
#include <cstring>
#include <cerrno>
#include <cstdio>

using namespace std;

int main()
{
    try
    {
        thread().detach();
    } catch (const system_error & e) {
        cout<<"Error code value - "<<e.code().value()<<" ; Meaning - "<<e.what()<<endl;
        cout<<"Error no. - "<<errno<<" ; Meaning - "<<strerror(errno)<<endl;
    }
}

Output -
Error code value - 22 ; Meaning - Invalid argument
Error no. - 0 ; Meaning - Success
Run Code Online (Sandbox Code Playgroud)

Ton*_*roy 6

errno这些函数使用那些记录它们遇到错误的副作用的函数 - 这些函数是从不抛出异常的C库或OS函数. system_error是C++标准库用于何时使用文档库设备来抛出该异常.完全分开.最后,阅读你的文档!

  • @ tshah06`error_code`不是"设置".它是`system_error`异常的属性的类型(def).但是我们可以方便地说库函数*抛出`system_error`异常*从不使用/设置`errno`.这种二元性的存在只是因为你可以从C++调用C函数(通过`errno`进行C风格的错误处理).在"纯"C++中,异常是选择的错误处理机制,因此"纯"C++程序永远不必处理`errno`. (4认同)
  • @ tshah06 - 只要有人谈论"纯粹的"C++,它就会让我感到紧张; 它通常意味着意识形态而非工程视角.C++是一种多范式语言,良好的工程意味着选择最合适的方法来解决问题,而不考虑"纯粹"与"不纯"的概念.某些函数返回错误代码; 一些设置全局标志; 一些函数抛出异常; 一些功能中止程序.选择取决于错误是什么,适当的响应是什么,以及调用代码是否可以处理它.但是错误的**很奇怪. (4认同)