"internal" 与 "associated" 流缓冲区之间的区别

Difference between "internal" vs "associated" stream buffer

来自http://www.cplusplus.com/reference/ios/ios/rdbuf/

Some derived stream classes (such as stringstream and fstream) maintain their own internal stream buffer, to which they are associated on construction. Calling this function to change the associated stream buffer shall have no effect on that internal stream buffer: the stream will have an associated stream buffer which is different from its internal stream buffer (although input/output operations on streams always use the associated stream buffer, as returned by this member function).

http://www.cplusplus.com/reference/fstream/ifstream/rdbuf/ 上:

Returns a pointer to the internal filebuf object.

Notice however, that this is not necessarily the same as the currently associated stream buffer (returned by ios::rdbuf).

那么如果内部缓冲区不用于输入和输出操作,那么它是做什么用的呢?如果这意味着这两行可以 return 两个不同的对象,为什么这会有用?

std::stringstream ss;
ss.rdbuf();                          // (1) returns "internal" stream buffer?
static_cast<std::ios&>(ss).rdbuf();  // (2) returns "associated" stream buffer?

内部缓冲区用于输入和输出操作,直到使用其他参数调用 rdbuf 为止。然后它就坐在那里。

您随时可以通过调用

重新启用它
stream.basic_ios::rdbuf(stream.rdbuf());

请注意内部缓冲区,例如std::fstream 始终是流对象拥有和管理的 std::filebuf 对象,而关联的缓冲区可以是任何 streambuf 派生对象。流仅存储指向它的基 class 指针,不管理其生命周期。

另请注意,标准未使用术语“内部缓冲区”。该标准使用了一些不同的术语:

The class basic_ifstream<charT, traits> supports reading from named files. It uses a basic_filebuf<charT, traits> object to control the associated sequence. For the sake of exposition, the maintained data is presented here as:

sb, the filebuf object.

上面的“维护数据”就是cplusplus.com所说的“内部流缓冲区”。