Do we really need std::error_category and std::error_condition?

偶尔善良 提交于 2019-12-07 06:09:13

问题


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.

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.


回答1:


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.

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.

Edit: 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.



来源:https://stackoverflow.com/questions/45868539/do-we-really-need-stderror-category-and-stderror-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!