为什么空 streambuf 的流插入失败?

Why does stream insertion of an empty streambuf fail?

我在使用 simple file-slurp 并且我决定添加一些错误检查。我很惊讶一个空文件会出错。这也不会发生在每个空序列上,“”工作正常。我还验证了 rdbuf() 正在返回一个非空指针。

#include <iostream>
#include <sstream>
using namespace std;

int main(int, char**){
    istringstream in(""); // Succeeds if non-empty
    stringstream sstr;
    if (sstr << in.rdbuf()) { // Succeeds if I replace in.rdbuf() with ""
        cout << "Read Successful\n";
    }else{
        cout << "Read Failed\n";
    }
}

它设置了故障位,因为标准需要它。 (我现在觉得很傻。我以为我可能做错了什么。)2014 年 11 月草案第 27.7.3.6.3.9 节说:

If the function inserts no characters, it calls setstate(failbit) (which may throw ios_base::failure (27.5.5.4)).

为什么委员会决定让这种行为不同于其他序列插入(如 char* 和 string),后者不认为插入任何内容都是失败的,这仍然是一个谜。但我现在知道这不是滥用对象的失败。