配列割り当てポリシーは、複数のオブジェクトを連続して格納するための記憶領域の割り当てと開放を行うポリシークラスである。2相テンプレートと状態を持ち得るポリシークラスで構成される。通常は配列構築ポリシーと共に使用する。
配列割り当てポリシーが提供する機能は次の通り。
配列割り当てポリシーによって割り当てられた記憶領域は、割り当てを行ったポリシーオブジェクトへと返却されなければならない。スカラー割り当てポリシーとは異なり、割り当て済み記憶領域の所有権移動は行えない。
配列割り当てポリシーの初期化オブジェクトは、割り当てポリシーの内部状態の初期化に使用する。あるポリシーオブジェクトaから取得した初期化オブジェクトを用いて別のポリシーオブジェクトbを構築したとき、bはaと同値とみなせる内部状態を持つ。
配列割り当てポリシーと配列構築ポリシーを用いたコンテナの例を示す。
例 6.2. 配列割り当てポリシーと配列構築ポリシーを用いたコンテナ
template <typename T, class AP, class CP>
class myvector
:
public AP::template bind<sizeof(T)>::type,
public CP::template bind<T, typename AP::template bind<sizeof(T)>::type::size_type>::type
{
private:
typedef typename AP::template bind<sizeof(T)>::type allocation_policy;
typedef typename CP::template bind<T, typename allocation_policy::size_type>::type construction_policy;
public:
typedef T value_type;
typedef typename construction_policy::pointer pointer;
typedef typename construction_policy::const_pointer const_pointer;
typedef typename construction_policy::reference reference;
typedef typename construction_policy::const_reference const_reference;
typedef typename allocation_policy::size_type size_type;
private:
pointer begin_, end_;
public:
myvector(size_type, const_reference);
~myvector() throw();
const_pointer begin() const
{ return begin_; }
const_pointer end() const
{ return end_; }
private:
myvector(const myvector&);
myvector& operator=(const myvector&);
};
template <typename T, class AP, class CP>
myvector<T, AP, CP>::myvector(size_type n, const_reference v)
: allocation_policy(), construction_policy()
{
begin_ = static_cast<pointer>(allocation_policy::allocate(n));
try {
end_ = construction_policy::construct(begin_, n, v);
}
catch (...) {
allocation_policy::deallocate(begin_, n);
throw;
}
}
template <typename T, class AP, class CP>
myvector<T, AP, CP>::~myvector() throw()
{
construction_policy::destruct(begin_, end_);
allocation_policy::deallocate(begin_, end_ - begin_);
}
myvectorクラステンプレートは、配列割り当てポリシーと配列構築ポリシーを用いたホストクラスで、単純な構成の動的配列である。myvector内では、配列割り当てポリシーのバックエンドはallocation_policy、配列構築ポリシーのバックエンドはconstruction_policyという別名で参照される。
myvectorのコンストラクタは、次の順序で処理を行う。
割り当てポリシー(allocation_policy)を初期化する
構築ポリシー(construction_policy)を初期化する
割り当てポリシーのallocateを呼び、記憶領域を割り当てる
構築ポリシーのconstructを呼び、すべての要素を構築する
myvectorのデストラクタは、コンストラクタとは逆の順序で処理を行う。