std::exception 的导数如何将字符串从它们的构造函数传递到它的 what() 虚函数?

How do std::exception's derivatives pass the string from their constructor to its what() virtual function?

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

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() 重载,而不调用它。

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

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

有什么好的实现方法吗?

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

虽然不是普通的 std::string,因为复制它们可能会抛出错误。可能相当于 std::shared_ptr<std::string>.