简体   繁体   English

如何测试std :: error_code不是错误?

[英]How do I test that an std::error_code is not an error?

I have a method that returns an std::error_code . 我有一个返回std::error_code I am not particularly interested in the error message, only in whether or not the method succeeded. 我对错误消息不是特别感兴趣,只是方法是否成功。

What is the best way to test that an std::error_code represents a successful operation? 测试std::error_code表示成功操作的最佳方法是什么?

I came across the similar situation when working with the ASIO library. 在使用ASIO库时,我遇到了类似的情况。 As what one of their blog posts suggests, std::error_code is meant to be tested as follows: 正如他们的博客文章所暗示的那样, std::error_code如下方式进行测试:

std::error_code ec;
// ...    
if (!ec)
{
  // Success.
}
else
{
  // Failure.
}

Having dug a little deeper, I found this (much more recent) discussion in the C++ Standard Google group, which confirms the statement above but also raises questions about whether the current design of std::error_code is straightforward enough. 深入挖掘后,我在C ++标准Google小组中发现了这个 (更近期的)讨论,这证实了上述陈述,但也提出了关于std::error_code的当前设计是否足够简单的问题。

Long story short, if you need to simply tell errors from success, !static_cast<bool>(errorCode) is what you need. 简而言之,如果您只需要简单地告诉成功错误,那么!static_cast<bool>(errorCode)就是您所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM