您的成员变量m_body是一个引用:
std::istream& m_body;
^ reference
explicit MockStreamContainer(char* buffer, int offset, int nbytes):
m_sbuf(buffer + offset, buffer + offset + nbytes),
m_body(&m_sbuf), // Here you are passing a pointer to `std::streambuf`
// This is not an `std::istream` so the compiler
// is trying to create one using the single argument
// constructor.
//
// That worked. So you have a temporary `std::istream` object
//
// You can not bind a temporary object to a non const reference
// hence the compiler error.
m_size(nbytes)
{}
我会这样做:
#include <iostream>
struct mock_membuf : public std::streambuf
{
mock_membuf(char* begin, char* end) {
this->setg(begin, begin, end);
}
};
struct mock_stream: public std::istream
{
mock_membuf streamBuffer;
public:
mock_stream(char* buffer, int offset, int nbytes)
: std::istream(nullptr)
, streamBuffer(buffer + offset, buffer + offset + nbytes)
{
rdbuf(&streamBuffer);
}
};
int main()
{
char buffer[] = "I'm a buffer with embedded nulls\0and line\n feeds";
std::string line;
mock_stream in(buffer, 5, 10);
while (std::getline(in, line)) {
std::cout << "line: " << line << "\n";
}
return 0;
}