c++ - What did the author mean with his comment about the input of a user-defined type? -


this example extracted section 10.3.3 input of user-defined types book "the c++ programming language" second edition, b. stroustrup. code old still compiles minor changes. example:

#include <istream> #include <complex>  using namespace std;  istream& operator>>(istream& s, complex<double>& a) {     // input formats complex; "f" indicates float:     //     //   f     //   (f)     //   (f, f)      double re = 0, im = 0;     char c = 0;      s >> c;     if( c == '(' ) {         s >> re >> c;         if( c == ',' ) s >> im >> c;         if( c != ')' ) s.clear(ios::badbit);  // set state     }     else {         s.putback(c);         s >> re;     }      if( s ) = complex<double>(re, im);     return s; } 

despite scarcity of error-handling code, handle kinds of errors. the local variable c initilized avoid having value accidentally '(' after failed operation. final check of stream state ensures value of argument a changed if went well.

i failed understand phrase emphasized above.

if s >> c fails c not written to.

if c uninitialized , remains uninitialized @ point of test if( c == '(' ). reading uninitialized char causes undefined behaviour.

the author talking possible way undefined behaviour might manifest itself.


the suggested fix of char c = 0; relies on fact thats.putback(c); nothing if s not good(). ok, although imho clearer write:

char c; s >> c;  if ( !s )     return s; 

then reading code can see behaves in case of error; instead of having thread way through flow of function , check no other operations unexpected.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -