如何在不复制或搜索的情况下获取const stringstream缓冲区的长度?

Lig*_*ica 12 c++ std c++03

我有一个const std::stringstream想要找出其底层字符串缓冲区中有多少字节的愿望.

  • 我不能seekg到最后,tellg然后seekg重新开始,因为这些操作都不可用const.

  • 我不想得到str().size()因为str()返回副本,这可能不是一个微不足道的数据量.

我有什么好的选择吗?


(流本身const只是因为它是另一种类型的成员而呈现给我,并且我收到const对该类型对象的引用.该流表示"文档"的内容,其封装对象表示CGI响应我试图Content-Length从内部生成准确的HTTP标题行operator<<(std::ostream&, const cgi_response&).)

Cor*_*lks 7

我从来没有对流缓冲区感到满意,但这似乎对我有用:

#include <iostream>
#include <sstream>

std::stringstream::pos_type size_of_stream(const std::stringstream& ss)
{
    std::streambuf* buf = ss.rdbuf();

    // Get the current position so we can restore it later
    std::stringstream::pos_type original = buf->pubseekoff(0, ss.cur, ss.out);

    // Seek to end and get the position
    std::stringstream::pos_type end = buf->pubseekoff(0, ss.end, ss.out);

    // Restore the position
    buf->pubseekpos(original, ss.out);

    return end;
}

int main()
{
    std::stringstream ss;

    ss << "Hello";
    ss << ' ';
    ss << "World";
    ss << 42;

    std::cout << size_of_stream(ss) << std::endl;

    // Make sure the output string is still the same
    ss << "\nnew line";
    std::cout << ss.str() << std::endl;

    std::string str;
    ss >> str;
    std::cout << str << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

关键是,rdbuf()const但返回非const缓冲器,其然后可以被用来寻求.