我知道 error_code 是系统相关的,error_condition 是系统无关的,但这是否意味着如果我们在构造它们时指定值和类别,它们就会不同。例如:
std::error_code ecode(1, std::system_category());
std::error_condition econd(1, std::system_category());
if (ecode == econd)//无论我们在哪个平台,这个条件总是为真吗??
上述在 macOS 的 XCode 中是正确的,所以我想知道如果我们在其他平台上,是否总是如此,例如 window 。
如果是这样,为什么会出现这种情况,因为 ecode
是系统相关的,而 econd
是系统无关的?
最佳答案
他们不是。错误代码和条件的相等性由类别成员函数“等效”决定,您可以编写一个从不使任何代码和条件相等的类别。例如:
#include <system_error>
#include <iostream>
struct cat_type : std::error_category
{
const char *name() const noexcept { return "name"; }
std::string message(int) const { return "message"; }
bool equivalent(int, const std::error_condition &) const noexcept { return false; }
bool equivalent(const std::error_code &, int) const noexcept { return false; }
} cat;
int main() {
std::error_code ecode(1, cat);
std::error_condition econd(1, cat);
std::cout << (ecode == econd) << '\n';
}
这个程序打印 0 是因为 equivalent 的每个重载都被调用并且它们都返回 false,所以它们不相等。
但是,对于 std::system_category
,特别是标准要求 equivalent
函数具有默认行为(参见 N4800 第 18.5.2.5 节 syserr.errcat.objects 第 4 段),并且由于默认行为是将具有相同类别和值的代码和条件视为相等,因此它们将比较相等。
关于c++ - std::error_code 和 std::error_condition 从相同的值和相同的类别构造总是等价的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55578443/