与多个流相同的字符串

Pie*_*tro 2 c++ performance stl stream c++11

我必须将相同的字符串(例如日志消息)发送到多个流.
以下哪种解决方案效率最高?

  1. 为每个流重建相同的字符串并将其发送到流本身.

    outstr1 << "abc" << 123 << 1.23 << "def" << endl;  
    outstr2 << "abc" << 123 << 1.23 << "def" << endl;  
    outstr3 << "abc" << 123 << 1.23 << "def" << endl;  
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用字符串的运算符构建字符串一次,并将其发送到所有流.

    std::string str = "abc" + std::to_string(123) + std::to_string(1.23) + "def";  
    outstr1 << str;  
    outstr2 << str;  
    outstr3 << str;  
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用流构建字符串一次,并将其发送到所有流:

    std::stringstream sstm;  
    sstm << "abc" << 123 << 1.23 << "def" << endl;  
    std::string str = sstm.str();  
    outstr1 << str;  
    outstr2 << str;  
    outstr3 << str;  
    
    Run Code Online (Sandbox Code Playgroud)

部分或全部这些输出流可以在RAM磁盘上.

还有其他方法可以做同样的事情吗?

Kei*_*all 5

我会使用tee输出流.做一些像(伪代码):

allstreams = tee(outstr1, outstr2, outstr3);
allstreams << "abc" << 123 << 1.23 << "def" << endl;
Run Code Online (Sandbox Code Playgroud)

标准c ++库中似乎没有任何东西可以做到这一点,但Boost有一个.

另请参阅如何组合输出流的答案,以便输出一次多个位置?