C++: std::istream read and its calls to std::streambuf underflow

会有一股神秘感。 提交于 2019-12-11 03:55:01

问题


the following code simply tests how often underflow is called when using std::istream read on an std::stringbuf.

#include <iostream>
#include <vector>
#include <sstream>

class TestStringBuf : 
public std::stringbuf
{
public:

    int_type underflow()
    {
        std::cout<<"TestStringBuf underflow"<<std::endl;
        return std::stringbuf::underflow();
    }
};

int main(int argc, const char * argv[])
{
    TestStringBuf buf;
    std::iostream stream(&buf);

    stream << "tesr";

    std::vector<char> data(4);
    stream.read(&data[0], 4);

    for(int i=0; i<data.size(); ++i)
        std::cout<<data[i];
    std::cout<<std::endl;

    return 0;
}

the output is:

TestStringBuf underflow
TestStringBuf underflow
test

I expected underflow to be called only once, since I read exactly the amount of bytes present in the get area, so why should it underflow again? Is this the expected behavior? I am asking because my custom underflow method can potentially block for a long time to read new data, so the second call to underflow is not very desirable in this case.

I am on Osx using clang 3.1 and libc++.

Thank you!

Update:

I just made a completely seperate test and it seems to me that this is a weirdness in the libc++ implementation since this does not happen with libstd++. can someone test this with other implementations? is this a bug or just an implementation difference (feels pretty buggy to me). I updated the code above so you can copy and paste it into any main.cpp.

Update2:

After all it was a bug in libc++, see: http://llvm.org/bugs/show_bug.cgi?id=13113 . If you compile libc++ yourself the bug should be gone, I will try that soon.


回答1:


The C++ standard explicitly allows the implementation of std::basic_stringbuf to store the character sequence in a std::basic_string instead of using the internal buffer of std::basic_streambuf.



来源:https://stackoverflow.com/questions/11037818/c-stdistream-read-and-its-calls-to-stdstreambuf-underflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!