命名空间
变体
操作

std::ios_base::pword

来自 cppreference.cn
< cpp‎ | io‎ | ios_base
 
 
 
 
void*& pword( int index );

首先,分配或调整私有存储(void* 的动态数组或其他可索引数据结构)的大小,使其足以使 index 成为一个有效索引,然后返回对私有存储中索引为 indexvoid* 元素的引用。

该引用可能因对此 ios_base 对象的任何操作(包括对 pword() 的另一次调用)而失效,但存储的值会保留,因此稍后使用相同的索引从 pword(index) 读取将产生相同的值,直到下一次调用 std::basic_ios::copyfmt()。该值可用于任何目的。元素的索引必须通过 xalloc() 获取,否则行为未定义。新元素被初始化为空指针

如果函数失败(可能由分配失败引起)且 *thisbasic_ios<> 对象或子对象的基类子对象,则调用 std::basic_ios<>::setstate(badbit),这可能会抛出 std::ios_base::failure

目录

[编辑] 参数

index - 元素的索引值

[编辑] 返回值

元素的引用。

[编辑] 异常

设置 badbit 时可能会抛出 std::ios_base::failure

[编辑] 注意

如果存储在 pword 中的指针需要管理,可以使用 register_callback() 来安装根据需要执行深拷贝或解除分配的处理程序。

[编辑] 示例

使用基类 pword 存储来对派生流对象进行运行时类型识别。

#include <iostream>
 
template<class CharT, class Traits = std::char_traits<CharT>>
class mystream : public std::basic_ostream<CharT, Traits>
{
public:
    static const int xindex;
 
    mystream(std::basic_ostream<CharT, Traits>& ostr) :
        std::basic_ostream<CharT, Traits>(ostr.rdbuf())
    {
        this->pword(xindex) = this;
    }
 
    void myfn()
    {
        *this << "[special handling for mystream]";
    }
};
 
// Each specialization of mystream obtains a unique index from xalloc()
template<class CharT, class Traits>
const int mystream<CharT, Traits>::xindex = std::ios_base::xalloc();
 
// This I/O manipulator will be able to recognize ostreams that are mystreams
// by looking up the pointer stored in pword
template<class CharT, class Traits>
std::basic_ostream<CharT, Traits>& mymanip(std::basic_ostream<CharT, Traits>& os)
{
    if (os.pword(mystream<CharT, Traits>::xindex) == &os)
        static_cast<mystream<CharT, Traits>&>(os).myfn();
    return os;
}
 
int main()
{
    std::cout << "cout, narrow-character test " << mymanip << '\n';
 
    mystream<char> myout(std::cout);
    myout << "myout, narrow-character test " << mymanip << '\n';
 
    std::wcout << "wcout, wide-character test " << mymanip << '\n';
 
    mystream<wchar_t> mywout(std::wcout);
    mywout << "mywout, wide-character test " << mymanip << '\n';
}

输出

cout, narrow-character test
myout, narrow-character test [special handling for mystream]
wcout, wide-character test
mywout, wide-character test [special handling for mystream]

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 36 C++98 如果引用失效,存储的值可能不会
被保留
存储的值将被保留
直到下次调用 copyfmt()
LWG 41 C++98 函数在失败时自行设置 badbit,
ios_base 不提供此类接口
badbit 由 basic_ios 设置
(如果 *this 是其基类子对象)

[编辑] 参阅

如有必要,调整私有存储的大小,并访问给定索引处的 long 元素
(公共成员函数) [编辑]
[静态]
返回一个程序范围内的唯一整数,可安全地用作 pword()iword() 的索引
(公共静态成员函数) [编辑]