【问题标题】:Custom Memory Allocator for STL mapSTL 映射的自定义内存分配器
【发布时间】:2012-07-07 14:19:27
【问题描述】:

这个问题是关于在插入 std::map 期间自定义分配器实例的构造。

这是std::map<int,int> 的自定义分配器以及一个使用它的小程序:

#include <stddef.h>
#include <stdio.h>
#include <map>
#include <typeinfo>

class MyPool {
public:
  void * GetNext() {
    return malloc(24);
  }
  void Free(void *ptr) {
    free(ptr);
  }
};

template<typename T>
class MyPoolAlloc {
public:
  static MyPool *pMyPool;

  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<typename X>
  struct rebind
  { typedef MyPoolAlloc<X> other; };

  MyPoolAlloc() throw() {
    printf("-------Alloc--CONSTRUCTOR--------%08x %32s\n", this, typeid(T).name());
  }

  MyPoolAlloc(const MyPoolAlloc&) throw()  {
    printf(" Copy Constructor ---------------%08x %32s\n", this, typeid(T).name());
  }

  template<typename X>
  MyPoolAlloc(const MyPoolAlloc<X>&) throw() {
    printf(" Construct T Alloc from X Alloc--%08x %32s %32s\n", this, typeid(T).name(), typeid(X).name());
  }

  ~MyPoolAlloc() throw() {
    printf(" Destructor ---------------------%08x %32s\n", this, typeid(T).name());
  };

  pointer address(reference __x) const { return &__x; }

  const_pointer address(const_reference __x) const { return &__x; }

  pointer allocate(size_type __n, const void * hint = 0) {
    if (__n != 1)
      perror("MyPoolAlloc::allocate: __n is not 1.\n");
    if (NULL == pMyPool) {
      pMyPool = new MyPool();
      printf("======>Creating a new pool object.\n");
    }
    return reinterpret_cast<T*>(pMyPool->GetNext());
  }

  //__p is not permitted to be a null pointer
  void deallocate(pointer __p, size_type __n) {
    pMyPool->Free(reinterpret_cast<void *>(__p));
  }

  size_type max_size() const throw() {
    return size_t(-1) / sizeof(T);
  }

  void construct(pointer __p, const T& __val) {
    printf("+++++++ %08x %s.\n", __p, typeid(T).name());
    ::new(__p) T(__val);
  }

  void destroy(pointer __p) {
    printf("-+-+-+- %08x.\n", __p);
    __p->~T();
  }
};

template<typename T>
inline bool operator==(const MyPoolAlloc<T>&, const MyPoolAlloc<T>&) {
  return true;
}

template<typename T>
inline bool operator!=(const MyPoolAlloc<T>&, const MyPoolAlloc<T>&) {
  return false;
}

template<typename T>
MyPool* MyPoolAlloc<T>::pMyPool = NULL;

int main(int argc, char *argv[]) {

  std::map<int, int, std::less<int>, MyPoolAlloc<std::pair<const int,int> > > m;
  //random insertions in the map
  m.insert(std::pair<int,int>(1,2));
  m[5] = 7;
  m[8] = 11;
  printf("======>End of map insertions.\n");
  return 0;
}

这是这个程序的输出:

--------Alloc--CONSTRUCTOR--------bffcdaa6 St4pairIKiiE 从 X Alloc 构造 T Alloc--bffcda77 St13_Rb_tree_nodeISt4pairIKiiEE St4pairIKiiE 复制构造函数 ----------------bffcdad8 St13_Rb_tree_nodeISt4pairIKiiEE 析构函数 ---------bffcda77 St13_Rb_tree_nodeISt4pairIKiiEE 析构函数---------bffcdaa6 St4pairIKiiE ======>创建一个新的池对象。 从 X Alloc 构造 T Alloc--bffcd9df St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d028 St4pairIKiiE。 析构函数 ---------------------bffcd9df St4pairIKiiE 从 X Alloc 构造 T Alloc--bffcd95f St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d048 St4pairIKiiE。 析构函数 ---------------------bffcd95f St4pairIKiiE 从 X Alloc 构造 T Alloc--bffcd95f St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d068 St4pairIKiiE。 析构函数 ---------------------bffcd95f St4pairIKiiE ======>地图插入结束。 从 X Alloc 构造 T Alloc--bffcda23 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d068。 析构函数---------bffcda23 St4pairIKiiE 从 X Alloc 构造 T Alloc--bffcda43 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d048。 析构函数---------bffcda43 St4pairIKiiE 从 X Alloc 构造 T Alloc--bffcda43 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d028。 析构函数---------bffcda43 St4pairIKiiE 析构函数 ---------bffcdad8 St13_Rb_tree_nodeISt4pairIKiiEE

输出的最后两列显示,每次在映射中插入时,都会构造 std::pair&lt;const int, int&gt; 的分配器。为什么这是必要的?有没有办法抑制这种情况?

谢谢!

编辑:此代码在 g++ 版本 4.1.2 的 x86 机器上测试。如果您希望在 64 位机器上运行它,您至少必须更改 return malloc(24) 行。更改为 return malloc(48) 应该可以。

【问题讨论】:

    标签: c++ memory-management stl map


    【解决方案1】:

    之所以如此,是因为分配器是为std::pair&lt;const int, int&gt; 分配的,但实现实际上需要分配一个更复杂的数据结构,这是其中的一个成员。虽然我希望需要构造和缓存实际的分配器,但每次都重新构造它并不违法。这是一个实现细节,如果不更改实现,您就无法逃避。创建的实际分配器类型是St13_Rb_tree_nodeISt4pairIKiiEE(错位名称)。

    【讨论】:

    • 如上面的输出所示,每次都构造它显然不是非法的。 STL/C++ 必须这样做有内在的原因吗?如果不是,那么如何更改实现以抑制它?
    • 在 C++03 中,允许实现假设分配器是无状态的(空的)。这样,创建副本几乎是免费的。在您的情况下,您可以让复制构造函数和赋值运算符复制内部指针,而不是每次都创建一个新的池。
    • @Prasoon 为什么要打扰?如果您摆脱跟踪语句,编译器将优化构造和销毁,因此不会花费您任何费用。
    • @Prasoon 这是一项功能。这与可怕的rebind 成员模板有关。正如 Scrubbins 所说,您有一个用于一种类型的分配器,而 map 需要一个用于另一种类型的分配器,因此它必须构造一个 via rebind。
    • @Prasoon:“虽然构造函数调用将被优化掉,但相应的内存分配调用可能不会。”什么内存分配?容器没有堆分配你的分配器;他们在堆栈上。而且您的分配器没有在构造函数的堆上分配内存。那么......你在说什么分配?
    【解决方案2】:

    在 MyPool.h(单例)中:

    class MyPool
    {
    ...
    public:
      static MyPool & GetInstance( void );
    private:
      MyPool(void);
    }
    

    在 MyPool.cpp 中:

    MyPool & MyPool::GetInstance( void )
    {
      static MyPool retval;
      return retval;
    }
    

    在 fooStdAllocator.h 中:

    #pragma once
    
    #include "MyPool.h"
    
    #pragma push_macro( "new" )
    #undef new
    #include <new>
    
    template <class T1> class fooStdAllocator;
    
    // Description:
    // Specialize for void
    template <> class fooStdAllocator<void>
    {
    public:
      typedef void * pointer;
      typedef const void* const_pointer;
      typedef void value_type;
      template <class U1> struct rebind { typedef fooStdAllocator<U1> other; };
    };
    
    template <class T1> class fooStdAllocator
    {
    public:
      // Description:
      // Typedefs
      typedef T1 value_type;
      typedef size_t size_type;
      typedef ptrdiff_t difference_type;
      typedef T1* pointer;
      typedef const T1* const_pointer;
      typedef T1& reference;
      typedef const T1& const_reference;
    
      // Description:
      // The rebind member allows a container to construct an allocator for some arbitrary type out of
      // the allocator type provided as a template parameter.
      template <class U1> struct rebind { typedef fooStdAllocator<U1> other; };
    
      // Description:
      // Constructors
      fooStdAllocator( void ) : pool(MyPool::GetInstance()) {};
      fooStdAllocator( const fooStdAllocator& other ) : pool(MyPool::GetInstance()) {};
      template <class U1> fooStdAllocator(const fooStdAllocator<U1>&) : pool(MyPool::GetInstance()) {};
    
      // Description:
      // Destructor
      ~fooStdAllocator( void ) {};
    
      // Description:
      // Returns the address of r as a pointer type. This function and the following function are used
      // to convert references to pointers.
      pointer address(reference r) const { return &r; };
      const_pointer address(const_reference r) const { return &r; };
    
      // Description:
      // Allocate storage for n values of T1.
      pointer allocate( size_type n, fooStdAllocator<void>::const_pointer hint = 0 )
      {
        // I would never do it that way:
        //pointer return_value = reinterpret_cast<pointer>( pool.GetNext() );
        // I would prefer to use the got size to allocate:
        pointer return_value = reinterpret_cast<pointer>( pool.GetNext(n) );
    
        if ( return_value == 0 )
          throw std::bad_alloc();
        return return_value;
      };
    
      // Description:
      // Deallocate storage obtained by a call to allocate.
      void deallocate(pointer p, size_type n)
      {
        pool.Free(p);
      };
    
      // Description:
      // Return the largest possible storage available through a call to allocate.
      size_type max_size() const
      {
        size_type return_value = 0xFFFFFFFF;
        return_value /= sizeof(T1);
        return return_value;
      };
    
      // Description:
      // Construct an object of type T1 at the location of ptr
      void construct(pointer ptr)
      {
        ::new (reinterpret_cast<void*>(ptr)) T1;
      };
    
      // Description:
      // Construct an object of type T1 at the location of ptr, using the value of U1 in the call to the
      // constructor for T1.
      template <class U1> void construct(pointer ptr, const U1& val)
      {
        ::new (reinterpret_cast<void*>(ptr)) T1(val);
      };
    
      // Description:
      // Construct an object of type T1 at the location of ptr, using the value of T1 in the call to the
      // constructor for T1.
      void construct(pointer ptr, const T1& val)
      {
        ::new (reinterpret_cast<void*>(ptr)) T1(val);
      };
    
      // Description:
      // Call the destructor on the value pointed to by p
      void destroy(pointer p)
      {
        p->T1::~T1();
      };
    private:
      MyPool &pool;
    };
    
    // Return true if allocators b and a can be safely interchanged. "Safely interchanged" means that b could be
    // used to deallocate storage obtained through a and vice versa.
    template <class T1, class T2> bool operator == ( const fooStdAllocator<T1>& a, const fooStdAllocator<T2>& b)
    {
      return true;
    };
    // Return false if allocators b and a can be safely interchanged. "Safely interchanged" means that b could be
    // used to deallocate storage obtained through a and vice versa.
    template <class T1, class T2> bool operator != ( const fooStdAllocator<T1>& a, const fooStdAllocator<T2>& b)
    {
      return false;
    };
    #pragma pop_macro( "new" )
    

    你可以这样使用它:

    std::map<keyT,valueT,std::less<keyT>,fooStdAllocator> your_map;
    

    【讨论】:

    • 我注意到 3 个构造函数中有 2 个不需要 reinterpret_cast。你能解释一下为什么这段代码应该有效吗? (我要到星期一才能使用机器。)
    • @PrasoonTiwari: reinterpret_casts: 可能是真的(可能适用于new 运营商),但我为你复制了一个工作和测试过的代码。 :)
    • @PrasoonTiwari:如果你想要单实例,你应该做单例。我为你修改代码。
    • 分配方法不应该使用pool.GetNext(n * sizeof T1)而不是pool.GetNext(n)吗? map 似乎正在为每个节点调用 allocate(1)。
    猜你喜欢
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    相关资源
    最近更新 更多