Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
};
like image 633
Baptistou Avatar asked Mar 04 '23 05:03

Baptistou


2 Answers

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

like image 181
NathanOliver Avatar answered Mar 09 '23 20:03

NathanOliver


  1. It can fail and you can either use return values for knowing the result or enable exceptions with std::ostream::exceptions method.

The example is for 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. They generally can.

  2. It is valid, but you must guarantee exceptions are not thrown out of them in fact. If an exception is attempted to be thrown out from the methods you provided, std::terminate will be called, since it is what happens for functions declared with noexcept when an exception is leaving them.

  3. The same is for std::istream.

like image 24
Arthur P. Golubev Avatar answered Mar 09 '23 21:03

Arthur P. Golubev