4

I strongly believed that std::basic_istream::operator>> is "transaction safe", i.e. if it fails, it leaves its operand unchanged. So, I was expected that for the following code

#include <iostream>
#include <sstream>

int main()
{
    std::stringstream ss("a");
    int i = 42;
    ss >> i; // extraction fails
    std::cout << i; // modifies i, WHY?!
}

Live on Coliru

the value of i would stay 42. However, starting from C++11 this doesn't seem to be the case anymore, and the operand is zeroed on failure. Quoting from cppreference.com (emphasize mine)

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set. (until 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() or std::numeric_limits<T>::min() is written and failbit flag is set. (since C++11)

Can anyone explain what is the reason for this modification? I find the behaviour undesirable, to say the least. Even if I compile with -std=c++98, gcc5.3 and clang3.6 still behave C++11-compliant.

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • I got trapped by this one, too. – 5gon12eder Jan 08 '16 at 03:00
  • @5gon12eder Yeah, me too, when trying to validate some input (while trying to answer a question on SO ;)), and was pulling my hair out trying to figure out what was going on... The question I asked is a bit off, as I ask for a reason, not a programming question per se. But I hope someone close to the C++ "crystal palace" (i.e. the standardization committee) may be able to provide a reason. – vsoftco Jan 08 '16 at 03:01
  • Also linked to in the other question is an answer in [What breaking changes are introduced in C++11?](http://stackoverflow.com/a/19523324) Also surprisingly all linked defect reports were opened in 1998 already but just took until C++11 to make it in. – AliciaBytes Jan 08 '16 at 03:11
  • @RaphaelMiedl Thanks for finding the duplicate question. The answer is not very clear, will try to look at some links within the comments. – vsoftco Jan 08 '16 at 03:23
  • `-std=c++98` doesn't change the library, only compiler rules (and even then incompletely) – Ben Voigt Jan 08 '16 at 03:36

0 Answers0