作者对用户定义类型的输入的评论是什么意思?

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

这是从 B. Stroustrup "The C++ Programming Language" 第二版的书 10.3.3 用户定义类型的输入 节中提取的示例。代码很旧,但仍然可以通过微小的更改进行编译。示例:

#include <istream>
#include <complex>

using namespace std;

istream& operator>>(istream& s, complex<double>& a)
{
    // input formats for a complex; "f" indicates a 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 ) a = complex<double>(re, im);
    return s;
}

Despite the scarcity of error-handling code, this will actually handle most kinds of errors. The local variable c is initilized to avoid having its value accidentally '(' after a failed operation. The final check of the stream state ensures that the value of the argument a is changed if everything went well.

我未能理解上面强调的短语。

考虑如果我们没有初始化会发生什么c:

char c;
s >> c;
if (c == '(') { ... }

我们不会检查 >> 是成功还是失败。因此,如果 c == '(',可能是以下两个原因之一:

  1. >> 成功,我们从 istream.
  2. 中检索到字符 '('
  3. >>失败了,但是创建c时恰好在内存中的随机字节是'('

如果你将c初始化为0,情况2是不可能的:如果操作失败,我们知道c会是0...所以我们肯定会知道,如果我们得到 '(',那是因为它来自 istream

如果 s >> c 失败,则不会写入 c

如果 c 未初始化,则它在测试点 if( c == '(' ) 时保持未初始化状态。读取未初始化的 char 会导致未定义的行为。

作者正在谈论这种未定义行为可能表现出来的可能方式。


char c = 0; 的建议修复依赖于这样一个事实:如果 s 不是 good()s.putback(c); 什么都不做。这没关系,尽管恕我直言,这样写会更清楚:

char c;
s >> c;

if ( !s )
    return s;

然后任何阅读代码的人都可以立即看到它在出现错误时表现正常;而不是必须在函数流中线程化并检查是否没有其他操作会做任何意外的事情。