简体   繁体   中英

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.

  1. Is there a case where ostream operator<< could fail?
  2. If no, why standard does not put noexcept specifier to these overloads?
  3. Is the following overload valid? good practice? commonly used?
  4. Same question for 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;
};

The reason none of the operator >> and operator << are marked as noexcept is because ofstd::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. If the operators were noexcept then you could not use them with a stream that has exceptions set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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