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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With