如何跟踪std::stringstream中的当前位置

how to keep track of the current position in std::stringstream

本文关键字:stringstream 位置 std 何跟踪 跟踪      更新时间:2023-10-16

我正在编写一个自定义日志记录器,我在std::stringstream中缓冲我的日志消息,并在std::stringstream足够大时将其刷新到文件(std::ofstream)(以节省一些IO延迟)。由于std::stringstream没有.size()方法,我使用seekgtellg:

template <typename T>
MyClass & operator<< (const T& val)
{
    boost::unique_lock<boost::mutex> lock(mutexOutput);
    output << val;  //std::stringstream output;
    output.seekg(0, std::ios::end);
    if(output.tellg() > 1048576/*1MB*/){
        flushLog();
    }
    return *this;
}

问题:在我看来,每当我调用这个方法时,它都会使用seekg开始从开始一直到结束计数字节,并使用tellg获得大小。我提出这种设计首先是为了节省一些IO时间,但是:这种连续计数是否会带来更大的成本(如果对该方法的调用数量很高,并且日志消息很少,就像大多数情况一样)?

是否有更好的方法来做到这一点?

和一个侧面的问题:1MB是一个很好的数字缓冲大小在一个正常的计算机现在?

谢谢

您可以使用ostringstream::tellp()来获取字符串的长度。下面的例子摘自http://en.cppreference.com/w/cpp/io/basic_ostream/tellp.

#include <iostream>
#include <sstream>
int main()
{
    std::ostringstream s;
    std::cout << s.tellp() << 'n';
    s << 'h';
    std::cout << s.tellp() << 'n';
    s << "ello, world ";
    std::cout << s.tellp() << 'n';
    s << 3.14 << 'n';
    std::cout << s.tellp() << 'n' << s.str();
}
输出:

<>之前011318你好,3.14号世界