0

Instead of atoi I use operator>> of stringstream in the following function in order to convert a string into an int.

int MyString::Int()
  {
  int f = 0;
  std::stringstream ss;
  ss << *this;
  ss >> f;
  return f;
  }

Is it guarenteed that operator>> does not touch integer variable "f" if it cannot convert the string data coming from "*this" into the integer?
Or can it happen that stringstream "ss" is set to failure by operator<< and therefore operator>> makes undefined behaviour because I do not check the state of the stream?

Edit: The answer is already here: istream behavior change in C++ upon failure There it is described that the behaviour changed in C++11 regarding if the value is left unchanged in some circumstances or set to zero if a conversion cannot be made. In my example above however the int variable is initialised anyway and therefore the return value would always be zero independently if the stream reaches eof before or the conversion is not possible.

Ernie Mur
  • 481
  • 3
  • 18

1 Answers1

1

ss >> f; may (and likely will) initially set f to 0 before trying to extract an integer from its internal buffer.

Regardless whether the extraction is a success (because of a previously or newly encountered error), you will not invoke UB. The operation will fail due to the incorrect stream state. It's perfectly valid and you can check for such states.

Fureeish
  • 12,533
  • 4
  • 32
  • 62
  • It seems that before C++11 the value was left untouched if e.g. the stream has an error. But in both cases there is no problem in my code because I initialise the int value – Ernie Mur Jan 12 '23 at 16:00