Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

I have a method that returns an 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?

like image 872
sdgfsdh Avatar asked Jan 17 '17 14:01

sdgfsdh


People also ask

What is Error_code in C++?

class error_code; (since C++11) std::error_code is a platform-dependent error code. Each std::error_code object holds an error code originating from the operating system or some low-level interface and a pointer to an object of type std::error_category, which corresponds to the said interface.


1 Answers

I came across the similar situation when working with the ASIO library. As what one of their blog posts suggests, std::error_code is meant to be tested as follows:

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.

Long story short, if you need to simply tell errors from success, !static_cast<bool>(errorCode) is what you need.

like image 57
Semisonic Avatar answered Sep 28 '22 12:09

Semisonic