命名空间
变体
操作

std::ios_base::xalloc

来自 cppreference.cn
< cpp‎ | io‎ | ios_base
 
 
 
 
static int xalloc();

返回一个唯一的(程序范围内的)索引值,该值可用于通过调用 iword()pword() 来访问 std::ios_base 私有存储中的一个 long 和一个 void* 元素。对 xalloc 的调用不分配内存。

此函数是线程安全的:多线程并发访问不会导致数据竞争。

(C++11 起)

有效地递增下一个可用的唯一索引。

目录

[编辑] 返回值

用于 pword/iword 索引的唯一整数。

[编辑] 示例

使用基类 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 2143 C++11 xalloc 不是线程安全的 已实现线程安全

[编辑] 另请参阅

如有必要,调整私有存储的大小,并访问给定索引处的 void* 元素
(public 成员函数) [编辑]
如有必要,调整私有存储的大小,并访问给定索引处的 long 元素
(public 成员函数) [编辑]