【问题标题】:How come the code below works?下面的代码如何工作?
【发布时间】:2013-01-26 01:06:11
【问题描述】:

众所周知,cout 在 VS2010 中没有缓冲(参见 Stephan Lavavej here 的帖子)。为什么下面的代码可以使用 cout 的缓冲区构造 ostream hexout?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    // Construct ostream hexout with cout's buffer and setup hexout to print hexadecimal numbers

    ostream hexout(cout.rdbuf());
    hexout.setf (ios::hex, ios::basefield);
    hexout.setf (ios::showbase);

    // Switch between decimal and hexadecimal output using the common buffer

    hexout << "hexout: " << 32 << " ";
    cout << "cout: " << 32 << " ";
    hexout << "hexout: " << -1 << " " ;
    cout << "cout: " << -1 << " ";
    hexout << endl;
}

【问题讨论】:

    标签: c++ visual-studio-2010 stream


    【解决方案1】:

    每个流都有一个与之关联的 basic_streambuf。 “无缓冲”仅仅意味着 basic_streambuf 不维护内部缓冲区(一块内存)来缓冲输入/输出,而是直接从文件(或控制台等)读取/写入文件。

    【讨论】:

    • 如果我理解正确,您的意思是hexout 将与cout 共享其streambuf 对象,该对象没有内存缓冲区。是这个主意吗?
    【解决方案2】:

    缓冲(或缺少缓冲)不会直接发生在std::stream 中。它出现在std::streambuf 中,该std::stream 中包含。流的作用是将内容转换为某种字符串表示形式,并将转换后的内容发送到流缓冲区。无论是一次发送一个字节还是以更大的块发送它是(我认为)实现定义的。

    您的代码有效,因为它都在一个线程中。当一切都在一个线程中时,您使用共享公共流缓冲区的两个流这一事实不是问题。对hexout.operator&lt;&lt; 的调用在对cout.operator&lt;&lt; 的调用开始之前完成。分号是一个序列点。

    创建两个线程,一个使用hexout,另一个使用cout,如果您不使用某种锁定机制保护写入,您可能会遇到麻烦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多