istream behavior change in C++ upon failure
Solution 1:
It seems as originally specified, the operator>>
s were broken in some cases (i.e. strictly speaking couldn't exist).
This is the "fix".
In a draft from early 2011, The Standard is basically the same in this regard as it was in 2003. However, in a library defect report opened by Matt Austern (in 1998!), num_get<>::get()
doesn't exist for short
and int
.
So they were changed to use the long
version, and check the read number falls within the correct range.
The defect report is here.
(Doesn't really explain why they didn't think they could keep the originally intended behaviour, but it is why this part of The Standard was changed.)
Solution 2:
It's more the C++ way of doing things to store zero in the non-const
reference input x
then returning the original value in case of error.
In order to keep the original value in case of an error condition the library would have to work with a temporary. It can't simply use the space provided by x
without storing the original value somewhere. Then it might also have to do a copy to x
at some point once the error conditions are known. How else would you get the original value if there's an error or the read input otherwise. So everyone pays the price regardless of whether they want this behavior or not.
So returning the original value in case of error isn't C++ at all. If you want that behavior simply pay for it yourself - create a temporary and pass its non-const
reference to operator>>
, something like:
int x = 1;
int temp;
if (std::cin >> temp)
x = temp;
return x;