无缓冲 std Streambuf 实现
为了对序列化库进行一些快速测试,我想创建一个可以从套接字读取/写入的streambuf。我不想在streambuf中使用缓冲区,而是让套接字处理这个问题。我确信序列化库只会调用 std::istream::read 和 std::ostream::write 。快速浏览一下 Microsoft 的 basic_streambuf 实现就会发现,这些调用实际上直接转发到 xsputn
和 xsgetn
。
问题是:我可以从streambuf派生并仅实现xsputn和xsgetn,并确保使用我的实现的流将始终调用这些方法,而不是sync/overflow/underflow/pback/...?或者我应该覆盖同步等以返回错误,或者标准是否保证默认实现没问题?最好这应该在任何通用平台上工作,并且我不能使用 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;
};
for some quick testing of a serialization library I want to create a streambuf that can read/write to/from a socket. I do not want to use a buffer in the streambuf, but let the socket handle this. I am sure the serialization lib will only call std::istream::read
and std::ostream::write
. A quick look at Microsoft's basic_streambuf implementation shows that these calls are practically directly forwarded to xsputn
and xsgetn
.
The question is: can I derive from a streambuf and just implement xsputn and xsgetn, and be sure that the streams that use my implementation will always call these methods, and not sync/overflow/underflow/pback/... ? Or else should I override sync etc to return errors, or does the standard guarantee that the default implementations are fine? Preferrably this should work on any common platform, and I cannot use the boost::iostreams.
Practically I'd use something like this:
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;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有缓冲区,(几乎?)不可能实现 std::streambuf。您必须重载
underflow
和overflow
,因为std::streambuf
的许多公共接口不会通过xsputn< /code> 或
xsgetn
。例如sputc
、sbumpc
等。甚至sputn
也不能保证引起调用xsputn
,具体取决于xsputn
的状态内部缓冲区和特定的 std::streambuf 实现。It's (almost?) impossible to implement a
std::streambuf
without a buffer. You will have to overloadunderflow
andoverflow
as many of the public interfaces tostd::streambuf
won't go viaxsputn
orxsgetn
. E.g.sputc
,sbumpc
, etc. Evensputn
is not guaranteed to cause a callxsputn
depending on the state of the internal buffer and the particularstd::streambuf
implementation.