0xb*_*00d 7 c++ boost boost-asio
我想返回一个boost::system::error_code指示是否可以解析主机/服务.主机/服务查找失败可能有多种原因(例如,网络连接问题或无效参数).
应该归还什么?
小智 5
您必须提出错误代码和类别才能创建error_code对象.下面是一个示例,假设错误是由于另一台主机拒绝连接:
error_code ec (errc::connection_refused, system_category());
return ec;
Run Code Online (Sandbox Code Playgroud)
errno使用系统类别时,您还可以将值作为错误代码传递.例如:
#include <fstream>
#include <cerrno>
#include <boost/system/system_error.hpp>
void foo ()
{
ifstream file ("test.txt");
if (!file.is_open ())
{
int err_code = errno;
boost::system::error_code ec (err_code
, boost::system::system_category ());
throw boost::system::system_error (ec, "cannot open file");
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这个库文档很少,所以我建议你查看头文件来解决问题.代码相当简单直接.
如果您的编译器支持C++ 11并且您愿意使用它,则此功能使其成为标准.据我所知gcc 4.6.1已经有了.这是一个简单的例子:
#include <cerrno>
#include <system_error>
std::error_code
SystemError::getLastError ()
{
int err_code = errno;
return std::error_code (err_code, std::system_category ());
}
void foo ()
{
throw std::system_error (getLastError (), "something went wrong");
}
Run Code Online (Sandbox Code Playgroud)
通常,error_code如果不需要抛出并使用system_error抛出描述系统故障的异常,库会传递对象.error_code无异常使用的另一个原因是当您需要跨不同线程发出错误信号时.但是C++ 11有一个跨线程传播异常的解决方案.
希望能帮助到你!
从外部不可能做到这一点resolve()。error_code&但是您可以通过使用以 an作为输出参数的重载之一来让它为您完成此操作:
iterator resolve(const query & q, boost::system::error_code & ec)iterator resolve(const endpoint_type & e, boost::system::error_code & ec)然后返回它设置的error_code。我相信这将会结束errno或h_errno在适当的时候。