C++ 异常返回类型为什么是 char*
有人能解释为什么自写的 C++ 异常,继承自异常返回一个 char * 而不是一个字符串?
Could someone explain why self-written C++ exception, that inherit from exception return a char * and not a string?
class myexception: public exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
} myex;
来源:http://www.cplusplus.com/doc/tutorial/exceptions/
推荐答案
由于 std::exception 被设计为所有异常的基类,因此接口的编写方式使得专业化不需要可能抛出的代码.他们可以使用它,但不需要它来实现接口.
Since std::exception was designed as a base class for all exceptions, the interface is written in such a way that specializations do not require code that may throw. They may use it, but they do not require it to implement the interface.
如果基础异常类需要 std::string
例如,则 std::out_of_memory 不能从它继承(因为在运行时构造一个要传递给构造函数的字符串可能无法工作)已经遇到内存不足的情况).
If the base exception class required std::string
for example, then std::out_of_memory could not inherit from it (because constructing a string to pass into the constructor may not work after the runtime has already encountered an out-of-memory condition).
仅基于 POD 类型的类的构造允许将 std::out_of_memory (以及可能在特殊情况下创建的其他异常)实现为特化.
The construction of the class based exclusively on POD types, allows the implementation of std::out_of_memory (and probably other exceptions that get created in extraordinary circumstances) as a specialization.
这并不意味着您不能在异常中使用 std::string (或其他任何东西).事实上,实践中的大多数异常都是从 std::logic_error 和 std::runtime_error 派生的,它们都接受一个 std::string 参数.
That doesn't mean that you cannot use std::string (or anything else) in your exceptions. In fact, most exceptions in practice are derived from std::logic_error and std::runtime_error, both of which take in a std::string argument.
注意:除非你真的需要这个,否则考虑从 std::runtime_error 或 std::logic_error 继承你的异常基类.它们级别更高,直接从 std::exception 继承比大多数情况需要的多.
Note: Unless you really need this, consider inheriting your base exception class from std::runtime_error or std::logic_error. They are higher level and inheriting from std::exception directly is more than most cases require.
相关文章