std::ios_base:: xalloc
      From cppreference.net
     
     
     | 
           
            
             static
            
            
             int
            
            xalloc
            
             (
            
            
             )
            
            
             ;
            
           
           | ||
       标签内的C++代码均未翻译,仅对说明性文字进行了本地化处理)
      
      
       返回一个唯一的(程序范围内的)索引值,该值可用于通过调用
       
        
         iword()
        
       
       和
       
        
         pword()
        
       
       访问
       
        std::ios_base
       
       私有存储区中的一个
       
        
         long
        
       
       类型元素和一个
       
        
         void
        
        
         *
        
       
       类型元素。调用
       
        xalloc
       
       不会分配内存。
      
| 此函数是线程安全的:多个线程的并发访问不会导致数据竞争。 | (since 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
          
          
           *
          
         
         元素 (公开成员函数) | |
| 必要时调整私有存储大小并访问指定索引处的
         
          
           long
          
         
         元素 (公开成员函数) |