名稱空間
變體
操作

std::ios_base::xalloc

來自 cppreference.com
< 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 成員函式) [編輯]