std::ios_base::iword
来自 cppreference.cn
long& iword( int index ); |
||
首先,分配或调整私有存储(long 或其他可索引数据结构的动态数组)的大小,使其足以使 index 成为有效索引,然后返回对私有存储的 long 元素的引用,索引为 index。
该引用可能会因对该 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>>
或传递到嵌入到标准流中的用户定义的格式化 facet。
[编辑] 参数
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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 36 | C++98 | 如果引用失效,存储的值可能不会 保留 |
存储的值会被保留 直到下次调用 copyfmt() |
LWG 41 | C++98 | 函数本身在失败时设置 badbit, 但 ios_base 不提供此类接口 |
badbit 由 basic_ios 设置(如果 *this 是它的基类子对象) |
[编辑] 参见
如有必要,调整私有存储的大小并访问给定索引处的 void* 元素 (公共成员函数) | |
[静态] |
返回程序范围唯一的整数,该整数可以安全地用作 pword() 和 iword() 的索引 (公共静态成员函数) |