【问题标题】:How do std::exception's derivatives pass the string from their constructor to its what() virtual function?std::exception 的衍生物如何将字符串从它们的构造函数传递给它的 what() 虚函数?
【发布时间】:2022-01-06 17:27:24
【问题描述】:

我想重新实现标准异常层次结构。

std::exception定义如下,根据documentation

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

现在,例如,std::logic_error 声明如下:

class logic_error : public exception {
public:
  explicit logic_error (const string& what_arg);
  explicit logic_error (const char* what_arg);
};

我的问题是,这样的实例化:std::logic_error("Error!") 如何在后台工作?

“错误!”字符串被传递给logic_error (const char* what_arg),并以某种方式将其值传递给实现中的what()重载,而不调用它。

这样做的一种方法可能是复制字符串并将其存储在某处(作为私有成员,在基类中),然后将其放入what()

我只是想澄清这是否是我应该做的。我知道异常应该尽可能轻量级。我想避免存储任何对象。

有没有好的方法来实现这个?

【问题讨论】:

  • 您的文档已过时 - C++ 中不再允许使用 throw()。现在改为noexcept
  • 这样做的一种方法可能是复制字符串并将其存储在某处(作为私有成员,在基类中),然后将其放入 what()。 不是在基础std::exception 类中。示例实现:std::exception 基类不存储任何数据。它是what() 返回不同的字符串,因为派生类覆盖了这个函数。 std::runtime_error 是层次结构中第一个存储字符串并覆盖方法的异常类,任何进一步的派生类只需将其传递给 std::runtime_error 构造函数。

标签: c++ exception


【解决方案1】:

是的,他们很可能将字符串存储在私有成员中。

虽然不是普通的std::string,因为复制那些可能会抛出。可能相当于std::shared_ptr<std::string>

【讨论】:

    猜你喜欢
    • 2021-01-23
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    相关资源
    最近更新 更多