![](/img/trans.png)
[英]Advantages of std::error_code/error_condition over errno?
[英]Are std::error_code and std::error_condition constructed from same value and same category always equivalent?
我知道 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 段),並且由於默認行為是考慮具有相同類別的代碼和條件和價值相等,他們將比較相等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.