std::ios_base::iword
來自 cppreference.com
long& iword( int index ); |
||
首先,分配或調整私有儲存(`long` 型別的動態陣列或其他可索引資料結構)的大小,使其足以使 index 成為一個有效索引,然後返回對私有儲存中具有索引 index 的 `long` 元素的引用。
該引用可能因對此 `ios_base` 物件的任何操作(包括另一次 `iword()` 呼叫)而失效,但儲存的值會被保留,因此稍後使用相同的索引讀取 iword(index) 將產生相同的值,直到下一次呼叫 std::basic_ios::copyfmt()。該值可用於任何目的。元素的索引必須透過先前呼叫 xalloc() 獲得,否則行為未定義。新元素初始化為 0。
如果函式失敗(可能由分配失敗引起)並且 *this 是 `basic_ios<>` 物件或子物件的基類子物件,則呼叫 std::basic_ios<>::setstate(badbit),這可能會丟擲 std::ios_base::failure。
目錄 |
[編輯] 注意
iword 儲存的典型用途是將資訊(例如自定義格式標誌)從使用者定義的 I/O 操縱器傳遞給使用者定義的 `operator<<` 和 `operator>>`,或傳遞給嵌入到標準流中的使用者定義的格式化方面。
[編輯] 引數
index | - | 元素的索引值 |
[編輯] 返回值
元素的引用。
[編輯] 異常
設定 badbit 時可能丟擲 std::ios_base::failure。
[編輯] 示例
執行此程式碼
#include <iostream> #include <string> struct Foo { static int foo_xalloc; std::string data; Foo(const std::string& s) : data(s) {} }; // Allocates the iword storage for use with Foo objects int Foo::foo_xalloc = std::ios_base::xalloc(); // This user-defined operator<< prints the string in reverse if the iword holds 1 std::ostream& operator<<(std::ostream& os, Foo& f) { if (os.iword(Foo::foo_xalloc) == 1) return os << std::string(f.data.rbegin(), f.data.rend()); else return os << f.data; } // This I/O manipulator flips the number stored in iword between 0 and 1 std::ios_base& rev(std::ios_base& os) { os.iword(Foo::foo_xalloc) = !os.iword(Foo::foo_xalloc); return os; } int main() { Foo f("example"); std::cout << f << '\n' << rev << f << '\n' << rev << f << '\n'; }
輸出
example elpmaxe example
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 36 | C++98 | 如果引用失效,儲存的值可能不會 保留 |
儲存的值會被保留 直到下次呼叫 `copyfmt()` |
LWG 41 | C++98 | 函式在失敗時自行設定 badbit, 但 `ios_base` 未提供此類介面 |
badbit 由 `basic_ios` 設定 (如果 *this 是其基類子物件) |
[編輯] 另請參閱
如有必要,調整私有儲存的大小,並訪問給定索引處的 void* 元素 (公共成員函式) | |
[靜態] |
返回一個程式範圍內的唯一整數,可安全地用作 pword() 和 iword() 的索引 (公共靜態成員函式) |