【问题标题】:C++ exception specification for iostream operator overloadingiostream 运算符重载的 C++ 异常规范
【发布时间】:2020-03-04 06:01:44
【问题描述】:

未指定调用ostream operator<< 是否会失败或抛出任何异常,我从未遇到过这种情况。

  1. 是否存在ostream operator<< 可能失败的情况?
  2. 如果不是,为什么标准不将noexcept 说明符放在这些重载中?
  3. 以下过载是否有效?好的做法?常用?
  4. istream operator>> 有同样的问题?
struct MyClass {
    int data;
    // I/O operators with noexcept specifier
    friend std::istream& operator>>(std::istream &in, MyClass &obj) noexcept;
    friend std::ostream& operator<<(std::ostream &out, const MyClass &obj) noexcept;
};

【问题讨论】:

    标签: c++ operator-overloading iostream noexcept


    【解决方案1】:

    operator &gt;&gt;operator &lt;&lt; 都没有标记为noexcept 的原因是std::basic_ios::exceptions。此成员函数存在于从 std::basic_ios 继承的所有对象中,并允许您配置流以针对某些故障模式引发异常。如果运算符是noexcept,那么您不能将它们与设置了异常的流一起使用。

    【讨论】:

    • 这感觉就像它只充分回答了第二个问题。话又说回来,OP 不应该在同一个问题中提出很多问题,所以就是这样。
    • @Chipster 对我来说,如果运算符是 noexcept,那么您不能将它们与设置了异常的流一起使用 涵盖了所有问题。 UB 是不做某事的好理由。
    • 它没有回答问题 1,我不认为。 OP似乎想要一个例子。但我想这就是我。
    • @Chipster 我真的需要展示一个设置了异常的流,以展示在遇到错误时如何抛出异常吗?
    • 我猜不是。不过会很好。不过,你有一个观点,所以无论如何我都会投赞成票。
    【解决方案2】:
    1. 它可能会失败,您可以使用返回值来了解结果或使用 std::ostream::exceptions 方法启用异常。

    该示例适用于 std::iostream。

    #include <iostream>
    
    int main () {
    
        std::cout.exceptions ( std::ios::failbit | std::ios::badbit );
    
        try {
    
            // operations with the stream ...
        
        } catch (const std::ios::failure & ex) {
    
        }
     
    }
    
    1. 他们通常可以。

    2. 它是有效的,但你必须保证异常不会被抛出。如果试图从您提供的方法中抛出异常,则会调用 std::terminate,因为当异常离开时,使用 noexcept 声明的函数会发生这种情况。

    3. std::istream 也是如此。

    【讨论】:

      猜你喜欢
      • 2014-02-21
      • 2010-09-30
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多