Safely overloading stream operator>>

前端 未结 3 1295
忘掉有多难
忘掉有多难 2021-02-01 07:49

There\'s a ton of information available on overloading operator<< to mimic a toString()-style method that converts a complex object to a string.

3条回答
  •  粉色の甜心
    2021-02-01 08:45

    1. How to indicate invalid data in the stream? Throw an exception?

    You should set the fail bit. If the user of the stream wants exception to be thrown, he can configure the stream (using istream::exceptions), and the stream will throw accordingly. I would do it like this, then

    stream.setstate(ios_base::failbit);
    
    1. What state should the stream be in if there is malformed data in the stream?

    For malformed data that doesn't fit the format you want to read, you usually should set the fail bit. For internal stream specific errors, the bad bit is used (such as, if there is no buffer connected to the stream).

    1. Should any flags be reset before returning the reference for operator chaining?

    I haven't heard of such a thing.


    For checking whether the stream is in a good state, you can use the istream::sentry class. Create an object of it, passing the stream and true (to tell it not to skip whitespace immediately). The sentry will evaluate to false if the eof, fail or bad bit is set.

    istream::sentry s(stream, true);
    if(!s) return stream;
    // now, go on extracting data...
    

提交回复
热议问题