我们真的需要 std::error_category 和 std::error_condition 吗? [英] Do we really need std::error_category and std::error_condition?

查看:41
本文介绍了我们真的需要 std::error_category 和 std::error_condition 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,在我了解 std::error_code 工作原理的过程中,我开始怀疑我们是否真的需要 std::error_conditionstd::error_category.我正在尝试实现 this教程,工作量不小而且它相当脆弱(我目前正试图弄清楚为什么这段代码会导致链接错误与重复符号.

So, on my journey to understand how std::error_code works I'm starting to wonder if we really need std::error_condition and std::error_category. I'm trying to implement what's in this and this tutorial and the amount of work is non-trivial along with it being fairly fragile (I'm currently stuck trying to figure out why this code causes linking errors with duplicate symbols.

子类化std::error_code不是更容易,添加一个message属性&方法,然后让 std::error_code 类似于定义错误代码的枚举?我正在努力理解为什么我需要 std::error_categorystd::error_condition.

Isn't it easier to subclass std::error_code, add a message property & method and then let std::error_code be comparable to an enum where error codes are defined? I'm struggling to understand why I need std::error_category and std::error_condition at all.

推荐答案

主要优点是 error_code 是一种可复制类型,可以在库之间传递,而无需涉及任何动态内存分配或模板,使其非常轻量级,并且易于使用.

The main advantage is that error_code is a copyable type that can be handed around from library to library without having to involve any dynamic memory allocation or templating, making it very light-weight, and easy to work with.

如果您正在编写一个完全独立的项目,那么是的,当您可以拥有自己的类型时,错误代码和类别似乎过于复杂.

If you are writing a fully self-contained project, then yes, error codes and categories seem overly complicated when you could just have your own type.

但是,在编写供其他人使用的库时,情况会发生变化(例如 ASIO,因为您链接了 think-async.com).你可以让一个库接收一个 error_code 实例,它可以干净有效地传递它,而无需知道使用库的代码,也不必犯每一个错误——处理函数被模板化为错误类型.

However, things change when writing a library meant to be used by other people (like ASIO, since you linked think-async.com). You can have a library receive an error_code instance, and it will be able to pass it around cleanly and efficiently without having to know anything about the code that is using the library, or having to make every error-handling function be templated on the error type.

在这种情况下,错误类别在处理多个错误源时很重要,因为根据错误源,给定的错误代码可能意味着两种不同的含义.

In that context, error categories are important when dealing with multiple error sources, as a given error-code could mean two different things based on the source of the error.

请注意,在您的第一个链接中,类别实际上是单例的.这样做是为了保持轻量级,因为复制一个指向保证永远不会被删除或修改的对象的指针是廉价、内存安全和线程安全的.

Notice, in your first link, how categories are actually singletons. This is done in the service of maintaining lightweightness, since copying a pointer to an object that is guaranteed to never be deleted or modified is cheap, memory-safe and thread-safe.

这篇关于我们真的需要 std::error_category 和 std::error_condition 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆