簡體   English   中英

如何跟蹤std :: stringstream中的當前位置

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

我正在編寫一個自定義記錄器,我在std::stringstream緩沖我的日志消息,並在std::stringstream足夠大時將其刷新到文件( std::ofstream )(以節省一些IO延遲)。 由於std::stringstream沒有seekg .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();
}

輸出:

0
1
13
18
hello, world 3.14

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM