std::ios_base::iword

来自cppreference.com
< cpp‎ | io‎ | ios base
 
 
 
 
long& iword(int index );

首先,充分地分配或重置能确保 index 是有效索引的私有存储(long 的动态数组或其他可索引数据结构),然后返回到带索引 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 {staticint foo_xalloc;std::string data;   Foo(conststd::string& s): data(s){}};   // 分配 Foo 对象所用的 iword 存储int Foo::foo_xalloc= std::ios_base::xalloc();   // 如果 iword 保有 1,那么此用户定义 operator<< 以逆序打印字符串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());elsereturn os << f.data;}   // 此输入/输出操纵符在 0 与 1 间翻转在 iword 存储的数字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 没有提供这样的接口
basic_ios 设置 badbit
(如果 *this 是它的基类子对象)

[编辑]参阅

若需要则调整私有存储的大小,并访问位于给定索引的 void* 元素
(公开成员函数)[编辑]
[静态]
返回能安全用作 pword()iword() 的索引的程序范围内独有的整数
(公开静态成员函数)[编辑]
close