C ++异常返回类型为何为char * [英] C++ exception return type why char*

查看:88
本文介绍了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.

这篇关于C ++异常返回类型为何为char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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