如何通过自定义的 streambuf 设置流的 badbit

how to set the badbit of a stream by a customized streambuf

我有一个定制的 std::streambuf。类似于:

class mybuf : public std::streambuf {
  ...
  virtual std::streambuf::int_type underflow() {
    if(eof) {
     return traits_type::eof();
    }
    ...
  }
  ...
  std::istream stream(new mybuf(...));

通过在 underflow() 函数上返回 eof 来设置流的 eof 标志。

如何设置流的 badbit 标志? overflow() 函数应该抛出异常吗?

抛出异常确实是可行的方法。

请参阅 std::ios_base::iostate 的参考页,具体来说:

The badbit is set by the following standard library functions:

  • ...
  • Every stream I/O function if an exception is thrown by any member function of the associated stream buffer (e.g. sbumpc(), xsputn(), sgetc(), overflow(), etc)
  • ...