ためになるホームページ お問い合わせ




TOP > C++ > allocator
allocator
コンテナ用のメモリを管理する。各コンテナは、allocatorを持っており、メモリの確保・取得をする。
例えばvectorは、
template <class T, class Allocator = allocator<T> > class vector
なので、vector宣言時に自動的にデフォルトのallocatorを使用している。
当然、自分で実装したallocatorを使用する事もできる。

allocatorの主な処理は、
  • 動的確保
  • メモリの開放
  • コンストラクタの実行
  • デストラクタの実行
  • オブジェクトのポインタを返す

  • 独自allocatorの例
    #include <iostream>
    #include <vector>
    using namespace std;
    
    
    template <class T> class my_allocator {
    public:
      typedef size_t    size_type;
      typedef ptrdiff_t difference_type;
      typedef T*        pointer;
      typedef const T*  const_pointer;
      typedef T&        reference;
      typedef const T&  const_reference;
      typedef T         value_type;
      template <class U>
      struct rebind { 
        typedef my_allocator<U> other; 
      };
    
      /*! @brief  ポインタを返す  
          @param  x 参照オブジェクト
          @return ポインタ
      */
      pointer address(reference x) const { 
        return &x; 
      }
    
      /*! @brief  CONSTポインタを返す
          @param  x 参照オブジェクト
          @return CONSTポインタ
      */
      const_pointer address(const_reference x) const { 
        return &x; 
      }
    
      /*! @brief 動的確保
          @param n     確保する数
          @param *hint 確保するポインタ)
          @return 確保した先頭アドレス
      */
      pointer allocate(size_type n, const void* hint = 0) {
        return (pointer)operator new(n * sizeof(T));
      }
    
      /*! @brief メモリの開放
          @param p 開放するポインタ
          @param n 開放するサイズ
      */
      void      deallocate(pointer p, size_type n) {
        operator delete(p);
      }
    
      /*! @brief 最長シーケンスの長さを返す。
          @return 最長シーケンスの長さ
      */
      size_type max_size() const { 
        return (size_t)-1 / sizeof(T); 
      }
    
      /*! @brief コンストラクタ(初期化)の実行
          @param p    初期化対象ポインタ
          @param &val 初期化する値
      */
      void construct(pointer p, const T& val) {
        new ((void*)p) T(val);
      }
    
      /*! @brief デストラクタを呼ぶ
          @param p ポインタ
      */
      void destroy(pointer p) {
        (p)->~T();
      }
    
      /*! @brief 異なった型用
          @param n サイズ
          @return 確保した先頭アドレス
      */
      char* _Charalloc(size_type n) {
        return allocate(n);
      }
    };
    
    int main(int argc, char* argv[])
    {
      int a[] = {1,2,3,4,5};
      
      /// 独自のmy_allocatorを使う
      vector <int, my_allocator<int> > v(a,a+5);
      return 0;
      }
    
    






    Copyright 2007 ためになるホームページ All Rights Reserved.