Posted on October 28th, 2006 at 0:29 by fr3@K
C++ Standard Library 提供的每種 container template 都需要一個 allocator template parameter. Default 為 std::allocator<T>. 大多數 programmer 所知道的 allocator 使用時機就是這樣:
void foo ()
{
vector<int, some_allocator<int> > integer_list;
}
更進階的程序員則可能會在寫程序時用到 allocator 的 instance, 通常是讓多個 container 共用一個 allocator:
void bar ()
{
typedef some_allocator<int> alloc_type;
alloc_type alloc(...);
vector<int, alloc_type> integer_list0(alloc);
vector<int, alloc_type> integer_list2(alloc);
}
最近我開始在寫 function (尤其是 function template) 的時候做一個實驗, 多寫一個 overload - 以傳遞 allocator 來當 parameter. 類似下面這樣:
void faux ()
{
faux(std::allocator<void>());
}
template <class Alloc>
void faux (const Alloc& user_alloc)
{
std::vector<int, Alloc> my_vector(user_alloc);
// use "my_vector"...
}
如此, 可以讓使用者在需要時指定特定 allocator, 在沒指定的狀況下又可以使用標準默認的 allocator.
![]() |
|
| Previous Post « 無能無恥炸彈公投 « |
Next Post » New Features in C++0x » |







