Take from: cppreference
Until C++11:
If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.
Since C++11:
If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value,
std::numeric_limits<T>::max()
orstd::numeric_limits<T>::min()
is written and failbit flag is set.
Due to this change, this means that the following snippet:
int x = 1; std::cin >> x; return x;
in the event that the numerical conversion fails, will return 1
before C++11, and 0
otherwise.
Why would the standard committee introduce such a subtle breaking change? Or rather, what kind of code was possible prior to C++11 that warranted this change?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With