gpt4 book ai didi

c++ - Unicode 异常 what()

转载 作者:IT老高 更新时间:2023-10-28 13:24:24 25 4
gpt4 key购买 nike

或者,“俄罗斯人如何抛出异常?”

std::exception的定义是:

namespace std {
class exception {
public:
exception() throw();
exception(const exception&) throw();
exception& operator=(const exception&) throw();
virtual ~exception() throw();
virtual const char* what() const throw();
};
}

一个 popular school of thought用于设计异常层次结构的方法是从 std::exception 派生:

Generally, it's best to throw objects,not built-ins. If possible, you shouldthrow instances of classes that derive(ultimately) from the std::exceptionclass. By making your exception classinherit (ultimately) from the standardexception base-class, you are makinglife easier for your users (they havethe option of catching most things viastd::exception), plus you are probablyproviding them with more information(such as the fact that your particularexception might be a refinement ofstd::runtime_error or whatever).

但是面对Unicode,设计一个同时实现以下两个的异常层次结构似乎是不可能的:

  • 最终派生自 std::exception 以便在捕获站点使用
  • 提供 Unicode 兼容性,因此诊断不会被分割或乱码

想出一个可以用 Unicode 字符串构造的异常类很简单。但是标准规定 what() 必须返回一个 const char*,因此在某些时候必须将输入字符串转换为 ASCII。无论是在构建时完成还是在调用 what() 时完成(如果源字符串使用 7 位 ASCII 无法表示的字符),可能无法在不丢失保真度的情况下格式化消息。

您如何设计一个异常层次结构,将 std::exception 派生类的无缝集成与无损 Unicode 诊断相结合?

最佳答案

char* 并不表示 ASCII。您可以使用 8 位 Unicode 编码,如 UTF-8。 char 也可以是 16 位或更多,然后您可以使用 UTF-16。

关于c++ - Unicode 异常 what(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3760731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com