命名空间
变体
操作

std::ios_base::iword

来自 cppreference.cn
< cpp‎ | io‎ | ios_base
 
 
 
 
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() 的索引
(公共静态成员函数) [编辑]