std::ios_base:: pword
|
void
*
&
pword
(
int
index
)
;
|
||
首先,分配或调整私有存储空间(动态数组 void * 或其他可索引数据结构)的容量,使其足以使 index 成为有效索引,然后返回私有存储中索引为 index 的 void * 元素引用。
对此
ios_base
对象的任何操作(包括再次调用
pword()
)均可能使引用失效,但存储的值会被保留,因此后续使用相同索引读取
pword
(
index
)
将获得相同值,直至下一次调用
std::basic_ios::copyfmt()
。该值可用于任意用途。元素索引必须通过
xalloc()
获取,否则行为未定义。新元素初始化为
空指针
。
若函数执行失败(可能由分配失败引起)且
*
this
是
basic_ios<>
对象或其子对象的基类子对象时,将调用
std::
basic_ios
<>
::
setstate
(
badbit
)
,该操作可能抛出
std::ios_base::failure
异常。
目录 |
参数
| 索引 | - | 元素的索引值 |
返回值
对元素的引用。
异常
当设置 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
类型元素
(公开成员函数) |
|
|
[static]
|
返回一个程序范围内唯一的整数值,该值可安全用作
pword()
和
iword()
的索引参数
(公开静态成员函数) |