Reputation: 141
I am trying to use the non-throwing version of std::filesystem::remove_all
, I have something like:
bool foo()
{
std::error_code ec;
std::filesystem::remove_all(myfolder, ec);
if (ec.value())
{
// failed to remove, return
return false;
}
}
Is this the correct way to use error_code
?
My reasoning:
I read this:
The overload taking a std::error_code& parameter sets it to the OS API error code if an OS API call fails, and executes ec.clear()
Now here:
clear - sets the error_code to value 0 in system_category
Now I used this to imply error_code == 0 => No error. error_code != 0 => error
.
I really can't any much examples of uses of error_code
. I just want to determine if all the files have been removed or not.
Upvotes: 1
Views: 1040
Reputation: 275500
There is a difference between ec.value()
and ec != std::error_code{}
; in the case where the error code in ec
is a different error category than system error and has a value of 0
, the first will return false, while the second will return true.
Error codes are a tuple of categories and value. Looking only at the value is a tiny bit of "code smell".
In this case, I don't think it is possible for the error code to have anything except the system category. And it would be bad form for a non-system error category to use the value 0 for an actual error.
If there was no error (value 0) with a non-system error code, treating it like an error is probably a bad idea. So maybe you shouldn't be checking the category.
Finally, if (ec.value())
is a verbose way of saying if (ec)
. I'd use the explicit operator bool() const
instead of calling .value()
.
Another option is:
if (-1 == std::filesystem::remove_all(myfolder, ec)) {
// failed to remove, return
return false;
}
Upvotes: 2