Is it guaranteed that standard extraction operator>> does not change argument in case of failure?

十年热恋 提交于 2019-12-11 04:19:58

问题


If calling something like input_stream >> i; where i is of arithmetic type, throws exception or sets badbit etc., is it guaranteed that i has not changed?


回答1:


Before C++11, the value was left as it was, [reference]:

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)

But after C++11, no. It is set to 0 if extraction fails (same reference):

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)




回答2:


Referring to the cppreference documentation for std::basic_istream::operator>> std::num_get::get, std::num_get::do_get :

1-4) Behaves as a FormattedInputFunction. After constructing and checking the sentry object, which may skip leading whitespace, extracts an integer value by calling std::num_get::get()

And then

Stage 3: conversion and storage:
[...]
- If the conversion function fails to convert the entire field, the value ​0​ is stored in v



来源:https://stackoverflow.com/questions/40828481/is-it-guaranteed-that-standard-extraction-operator-does-not-change-argument-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!