为什么以下代码有效?

时间:2013-01-26 01:06:12

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

众所周知,在VS2010中没有提供cout(参见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;
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

您的代码有效,因为它只在一个线程中。当所有内容都在一个线程中时,您使用共享公共流缓冲区的两个流的事实不是问题。在hexout.operator<<的呼叫开始之前,对cout.operator<<的呼叫已完成。分号是一个序列点。

创建两个线程,一个使用hexout,另一个使用cout,如果不使用某种锁定机制保护写入,则可能会很乱。