1

这是我的错误还是 boost::asio::streambuf 实现中的错误?在向下的情况下,我创建 boost::asio::streambuf 的实例,然后创建 std::istream 的实例并将 3 int 写入 streambuf。然后我需要从 streambuf 中读取 int,而它包含数据。

我不明白为什么 is.eof() 在这段代码中总是返回 false。

我写了下一个案例:

    void TestCase()
    {
        boost::asio::streambuf sbuf;

        try {
            std::istream is(&sbuf);

            // put three raw ints in streambuf
            for( int i=0; i<3; i++ ) {
                auto sz = boost::asio::buffer_copy( 
                    sbuf.prepare(sizeof(int)),
                    boost::asio::buffer(&i, sizeof(int)) 
                );
                sbuf.commit(sz);
            }

            // read from streambuf while not end-of-stream occured  
            // (not work! why? what wrong?)
            while( !is.eof() ) {
                int t;
                auto sz = is.readsome( reinterpret_cast<char*>(&t), sizeof(int) );

                // this work, but why is.eof() not detect end of stream condition 
                // on next iteration if this condition are commented?
                // ( wrong value of t are correct in this example )
                #if 1
                if( sz < sizeof(int) )
                    break;
                #endif

                std::cout << t << ' ';
            }
        }
        catch(std::exception& e) {
            std::cout << e.what() << std::endl;
        }
    }  
4

0 回答 0