std::error_code 和 std::error_condition 是否由相同的值和相同的类别构造,始终是等价

Are std::error_code and std::error_condition constructed from same value and same category always equivalent?

本文关键字:std error 是否 code condition      更新时间:2023-10-16

我知道error_code是系统依赖的,error_condition是系统无关的,但这是否意味着如果我们在构造它们时指定值和类别,它们会有所不同。例如:

std::error_code ecode(1, std::system_category());

std::error_condition econd(1, std::system_category());

if (ecode == econd) // is this condition always true no matter what platform we are in??

以上情况在macOS的XCode中是正确的,所以我想知道如果我们在其他平台(例如Windows(中是否总是如此。

如果是这样,为什么会这样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,因为调用了每个等效重载,并且它们都返回 false,因此它们不相等。

但是,对于

std::system_category具体而言,标准要求equivalent函数具有默认行为(请参阅 N4800 第 18.5.2.5 节 syserr.errcat.objects 第 4 段(,并且由于默认行为是将具有相同类别和值的代码和条件视为相等,因此它们将进行比较。

相关文章: