2013-04-05 24 views
4

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

我做了一个小测试程序来理解这一点,但仍然有点困惑。请帮忙。这些功能是C库或OS功能从未抛出异常 -

#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 
+1

您的标题引用了所谓的'error_code',但您的代码没有提及它。 – 2013-04-05 06:14:28

+1

@Keith:e.code()函数返回error_code的对象,它的值正在用值函数读取。 – tshah06 2013-04-05 06:20:07

回答

6

errno由那些记录,作为其遇到错误的副作用的功能使用。 system_error是由C++标准库使用的,当你使用图书馆设施来记录该异常时。完全分开。最终,阅读您的文档!

+0

那么我们可以方便地说那些设置error_code的库函数不会使用/设置errno吗? – tshah06 2013-04-05 06:22:29

+4

@ tshah06'error_code'没有被设置。它是'system_error'异常属性的类型(def)。但是我们可以方便地说库函数*抛出'system_error'异常*从不使用/设置'errno'。这种双重性的存在只是因为你可以从C++调用C函数(通过errno执行C风格的错误处理)。在“纯粹的”C++异常中是错误处理机制的选择,所以“纯粹的”C++程序将永远不必处理“errno”。 – 2013-04-05 06:31:32

+0

@Arne:有道理。我想现在我已经很清楚了。谢谢。 – tshah06 2013-04-05 07:01:37