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.

另見