开发者

In what state should my overridden >> operator leave my object when the input stream contains invalid data?

开发者 https://www.devze.com 2022-12-21 21:22 出处:网络
Say I have overridden the >> operator for a class like below: friend istream& operator>>(istream& in, MyObject& obj)

Say I have overridden the >> operator for a class like below:

friend istream& operator>>(istream& in, MyObject& obj)
{
    ...
    if (in.fail())
        // What do开发者_C百科 I do here?  Should obj be returned unmodified?
    ...
}

and say that the input stream is in a fail state because the data there means that I cannot get a valid MyObject out of it. How should I leave the obj object?


The way that most code that performs stream I/O is written is:

MyObject obj;

if ( ! ( cin >> obj ) ) {
   // handle error
}

In other words, it is up to the user of operator >> to check that the operation worked, and the way to do that is to test the state of the stream, not the object. I'd also observe that except for low-level "value" objects like strings and integers, stream input via operator >> is not normally very useful because it requires that the object being read is default constructible, and most higher level objects are not.


Ideally, you just need to manipulate the state bits when your operator>> can't read what it is supposed to be read. In other words, the user should check if the stream is in a valid state before using your object.


I would recommend leaving it unmodified and throwing an exception, since the client code violates an essential assumption. To leave the object unmodified even if the stream fails half-way, read the contents into a temporary MyObject, and swap them when complete.

0

精彩评论

暂无评论...
验证码 换一张
取 消