我有一个 Visual Studio 2008 C++ 项目,我正在尝试将数据从多个类序列化为自定义std::streambuf
实现。
带有序列化的数据类:
struct Header { /*...*/ };
inline std::ostream& operator<<( std::ostream& os, const Header& h )
{
/* serialize the members of Header here */
os.write( h.some_member, sizeof( h.some_member ) );
return os;
}
struct Info { /*...*/ };
inline std::ostream& operator<<( std::ostream& os, const Info& i )
{
/* serialize the members of Info here */
return os;
}
streambuffer 实现提供缓冲的 i/o 和覆盖underflow
和overflow
.
class MyStreamBuf : public std::streambuf
{
public:
MyStreamBuf() { InitBuffers(); };
private:
void InitBuffers()
{
recv_buffer_.resize( buff_size );
send_buffer_.resize( buff_size );
setg( &recv_buffer_[ 0 ], &recv_buffer_[ 0 ], &recv_buffer_[ 0 ] );
setp( &send_buffer_[ 0 ], &send_buffer_[ 0 ] );
};
enum { buff_size = 512 };
std::vector< char_type > recv_buffer_;
std::vector< char_type > send_buffer_;
int_type underflow() { /* ... */ };
int_type overflow( char_type c )
{
*pptr() = c;
pbump( 1 );
// if the buffer is full, flush the data
if( pptr() == epptr() )
flush();
return c;
};
void flush()
{
std::ptrdiff_t n = pptr() - pbase();
int written = /* send n bytes to the data destination */
pbump( -written );
};
}; // class MyStreamBuf
我的预期用途是这样的:
Header h( /* some useful info */ );
Info i( /* some useful info */ );
MyStreamBuf dest;
std::iostream my_stream( &dest );
dest << h << i; // MyStreambuf::overflow() is never called!
但是,MyStreambuf::overflow
永远不会被调用。我需要做什么才能将数据放入我的缓冲区?
谢谢,保罗