是否存在与将数据流式传输到 c++ 异常类相关的任何危险



请考虑以下代码:

throw my_exception() << "The error " << error_code << " happened because of " << reasons;

支持代码如下所示:

class my_exception
{
   public:
      template <typename T>
      my_exception & operator << (const T & value)
      {
         // put the value somewhere
         return *this;
      }
      // etc.
};

与下面的替代方案相比,有什么理由会使这种throw变得危险或效率低下吗?

std::stringstream s;
s << "The error " << error_code << " happened because of " << reasons;
throw my_exception(s.str());

您通过多个函数调用(operator<<重载(构造异常对象,所有这些调用都发生在引发异常之前。 这与正常的程序执行没有什么不同。

唯一的潜在问题是,如果异常对象的构建中抛出某些内容(例如,没有足够的内存可用于保存构建的错误字符串(,则可能会引发不同的异常。

因此,这样做本身并没有什么危险。

最新更新