public member function
<ios> <iostream>

std::basic_ios::rdbuf

get (1)
basic_streambuf<char_type,traits_type>* rdbuf() const;
set (2)
basic_streambuf<char_type,traits_type>* rdbuf (basic_streambuf<char_type,traits_type>* sb);
Get/set stream buffer
The first form (1) returns a pointer to the stream buffer object currently associated with the stream.

The second form (2) also sets the object pointed by sb as the stream buffer associated with the stream and clears the error state flags.

If sb is a null pointer, the function automatically sets the badbit error state flags (which may throw an exception if member exceptions has been passed badbit).

Some derived stream classes (such as string streams and file streams) 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).

参数

sb
Pointer to a basic_streambuf object with the same template parameters as the basic_ios object.
char_typetraits_type 是成员类型,分别定义为第一个和第二个类模板参数的别名(参见 basic_ios types)。

返回值

A pointer to the stream buffer object associated with the stream before the call.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// redirecting cout's output thrrough its stream buffer
#include <iostream>     // std::streambuf, std::cout
#include <fstream>      // std::ofstream

int main () {
  std::streambuf *psbuf, *backup;
  std::ofstream filestr;
  filestr.open ("test.txt");

  backup = std::cout.rdbuf();     // back up cout's streambuf

  psbuf = filestr.rdbuf();        // get file's streambuf
  std::cout.rdbuf(psbuf);         // assign streambuf to cout

  std::cout << "This is written to the file";

  std::cout.rdbuf(backup);        // restore cout's original streambuf

  filestr.close();

  return 0;
}

This example uses both function forms: first to get a pointer to a file's basic_streambuf object and then to assign it to cout.

数据竞争

Accesses (1) or modifies (2) the stream object.
并发访问同一个流对象可能导致数据争用。

异常安全

基本保证:如果抛出异常,流处于有效状态。
It throws an exception of member type failure if sb is a null pointer and member exceptions was set to throw for badbit.

另见