简体   繁体   English

iostream 运算符重载的 C++ 异常规范

[英]C++ exception specification for iostream operator overloading

It is not specified if call to ostream operator<< can fail or throw any exception and I have never encounter this.未指定调用ostream operator<<是否会失败或抛出任何异常,我从未遇到过这种情况。

  1. Is there a case where ostream operator<< could fail?是否存在ostream operator<<可能失败的情况?
  2. If no, why standard does not put noexcept specifier to these overloads?如果不是,为什么标准没有将noexcept说明符放在这些重载中?
  3. Is the following overload valid?以下重载有效吗? good practice?好的做法? commonly used?常用?
  4. Same question for istream operator>> ? istream 运营商的同样问题>>
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;
};

The reason none of the operator >> and operator << are marked as noexcept is because ofstd::basic_ios::exceptions . operator >>operator <<都没有被标记为noexcept的原因是std::basic_ios::exceptions This member function is present in all objects that inherit from std::basic_ios and allows you to configure the stream to throw exceptions for certain failure modes.此成员 function 存在于从std::basic_ios继承的所有对象中,并允许您配置 stream 以针对某些故障模式抛出异常。 If the operators were noexcept then you could not use them with a stream that has exceptions set.如果运算符为noexcept ,则您不能将它们与设置了异常的 stream 一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM