为了快速测试序列化库,我想创建一个能够对套接字进行读写的streambuf。我不想在streambuf中使用缓冲区,但让套接字处理这个问题。我确信序列化库只会调用std::istream::read和std::ostream::write。快速浏览一下微软的basic_streambuf实现就会发现,这些调用实际上是直接转发到xsputn和xsgetn的。
问题是:我是否可以从streambuf派生并只实现xsputn和xsgetn,并确保使用我的实现的流将始终调用这些方法,而不是sync/overflow/underflow/pback/...?或者我应该重写sync etc以返回错误,或者标准是否保证默认实现是正常的?最好是在任何公共平台上都能工作,而且我不能使用boost::iostreams。
实际上,我会使用这样的东西:
class socket_buf : public std::streambuf
{
public:
//Socket is a class with std::stream-like read/write methods
MyBuf( Socket& s ) : sock( s ) {}
protected:
std::streamsize xsputn( const char* s, std::streamsize n )
{
return sock.write( s, n );
}
std::streamsize xsgetn( char* s, std::streamsize n )
{
return sock.read( s, n );
}
private:
Socket& sock;
};发布于 2011-08-18 20:04:25
它(几乎?)无法在没有缓冲区的情况下实现std::streambuf。您将不得不重载underflow和overflow,因为许多到std::streambuf的公共接口不会通过xsputn或xsgetn。例如sputc、sbumpc等。根据内部缓冲器的状态和特定std::streambuf实现,即使sputn也不能保证引起调用xsputn。
https://stackoverflow.com/questions/7107025
复制相似问题