Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ STL映射的自定义内存分配器_C++_Memory Management_Stl_Map - Fatal编程技术网

C++ STL映射的自定义内存分配器

C++ STL映射的自定义内存分配器,c++,memory-management,stl,map,C++,Memory Management,Stl,Map,这个问题是关于在插入std::map期间构造自定义分配器的实例 下面是一个用于std::map的自定义分配器以及一个使用它的小程序: #include <stddef.h> #include <stdio.h> #include <map> #include <typeinfo> class MyPool { public: void * GetNext() { return malloc(24); } void Free(v

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

下面是一个用于
std::map
的自定义分配器以及一个使用它的小程序:

#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;
}
#包括
#包括
#包括
#包括
类MyPool{
公众:
void*GetNext(){
返回malloc(24);
}
无空隙(空隙*ptr){
免费(ptr);
}
};
模板
类MyPoolAlloc{
公众:
静态MyPool*pMyPool;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T*指针;
typedef const T*const_指针;
typedef T&reference;
类型定义常数T和常数U参考;
类型定义T值_类型;
模板
结构重新绑定
{typedef MyPoolAlloc other;};
MyPoolAlloc()抛出(){
printf(“----Alloc--CONSTRUCTOR------08x%32s\n”,this,typeid(T.name());
}
MyPoolAlloc(const MyPoolAlloc&)throw(){
printf(“复制构造函数-----------------%08x%32s\n”,this,typeid(T).name());
}
模板
MyPoolAlloc(const MyPoolAlloc&)throw(){
printf(“从X Alloc--%08x%32s%32s\n构造T Alloc”,this,typeid(T.name(),typeid(X.name());
}
~MyPoolAlloc()抛出(){
printf(“析构函数-----------------%08x%32s\n”,this,typeid(T).name());
};
指针地址(引用uux)常量{return&uuux;}
常量指针地址(常量引用)常量{return&\uuuux;}
指针分配(大小、类型、常量无效*提示=0){
如果(n!=1)
perror(“MyPoolAlloc::allocate:_n不是1。\n”);
if(NULL==pMyPool){
pMyPool=newmypool();
printf(“=======>创建新池对象。\n”);
}
返回reinterpret_cast(pMyPool->GetNext());
}
//__p不允许是空指针
无效解除分配(指针、大小、类型){
pMyPool->Free(重新解释铸造(u p));
}
大小\类型最大大小()常量抛出(){
返回大小\u t(-1)/sizeof(t);
}
void构造(指针、常量和值){
printf(“++%08x%s.\n”,uu p,typeid(T.name());
::新的(u p)T(u val);
}
无效销毁(指针\uu\p){
printf(“-+-+-+-%08x.\n”;
__p->~T();
}
};
模板
内联布尔运算符==(常量MyPoolAlloc&,常量MyPoolAlloc&){
返回true;
}
模板
内联布尔运算符=(常数MyPoolAlloc&,常数MyPoolAlloc&){
返回false;
}
模板
MyPool*MyPoolAlloc::pMyPool=NULL;
int main(int argc,char*argv[]){
std::map m;
//地图中的随机插入
m、 插入(标准::对(1,2));
m[5]=7;
m[8]=11;
printf(“===>地图插入结束。\n”);
返回0;
}
以下是该程序的输出:

-------Alloc--CONSTRUCTOR--------bffcdaa6 St4pairIKiiE Construct T Alloc from X Alloc--bffcda77 St13_Rb_tree_nodeISt4pairIKiiEE St4pairIKiiE Copy Constructor ---------------bffcdad8 St13_Rb_tree_nodeISt4pairIKiiEE Destructor ---------------------bffcda77 St13_Rb_tree_nodeISt4pairIKiiEE Destructor ---------------------bffcdaa6 St4pairIKiiE ======>Creating a new pool object. Construct T Alloc from X Alloc--bffcd9df St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d028 St4pairIKiiE. Destructor ---------------------bffcd9df St4pairIKiiE Construct T Alloc from X Alloc--bffcd95f St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d048 St4pairIKiiE. Destructor ---------------------bffcd95f St4pairIKiiE Construct T Alloc from X Alloc--bffcd95f St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE +++++++ 0985d068 St4pairIKiiE. Destructor ---------------------bffcd95f St4pairIKiiE ======>End of map insertions. Construct T Alloc from X Alloc--bffcda23 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d068. Destructor ---------------------bffcda23 St4pairIKiiE Construct T Alloc from X Alloc--bffcda43 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d048. Destructor ---------------------bffcda43 St4pairIKiiE Construct T Alloc from X Alloc--bffcda43 St4pairIKiiE St13_Rb_tree_nodeISt4pairIKiiEE -+-+-+- 0985d028. Destructor ---------------------bffcda43 St4pairIKiiE Destructor ---------------------bffcdad8 St13_Rb_tree_nodeISt4pairIKiiEE -------Alloc--构造函数----bffcdaa6 ST4Pairikie 从X Alloc构造T Alloc--bffcda77 St13_Rb_tree_nodeist4pairikie st4pairikie 复制构造函数------------------bffcdad8 St13\u Rb\u tree\u nodeist4pairikiie 析构函数-----------------bffcda77 St13\u Rb\u tree\u nodeist4pairikie 析构函数-----------------bffcdaa6 ST4Pairikie ====>创建新的池对象。 从X Alloc构造T Alloc——bffcd9df St4Pairikie St13_Rb_tree_nodeist4Pairikie +++++++0985d028 ST4Pairikie。 析构函数-----------------bffcd9df ST4Pairikie 从X Alloc构造T Alloc--bffcd95f st4pairikie St13_Rb_tree_nodeist4pairikie +++++++0985d048 ST4Pairikie。 析构函数-----------------bffcd95f St4Pairikie 从X Alloc构造T Alloc--bffcd95f st4pairikie St13_Rb_tree_nodeist4pairikie +++++++0985d068 ST4Pairikie。 析构函数-----------------bffcd95f St4Pairikie =======>地图插入结束。 从X Alloc构造T Alloc--bffcda23 st4pairikie St13_Rb_tree_nodeist4pairikie -+-+-+-0985d068。 析构函数-----------------bffcda23 St4Pairikie 从X Alloc构造T Alloc--bffcda43 St4Pairikie St13_Rb_tree_nodeist4Pairikie -+-+-+-0985d048。 析构函数-----------------bffcda43 St4Pairikie 从X Alloc构造T Alloc--bffcda43 St4Pairikie St13_Rb_tree_nodeist4Pairikie -+-+-+-0985d028。 析构函数-----------------bffcda43 St4Pairikie 析构函数-----------------bffcdad8 St13\u Rb\u tree\u nodeist4pairikie 输出的最后两列显示,每当有插入到映射中时,就会构造
std::pair
的分配器。为什么这是必要的?有没有办法抑制这种情况

谢谢


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

之所以如此,是因为分配器用于
std::pair
,但实现实际上需要分配一个更复杂的数据结构,它是其中的一个成员。虽然我希望实际的分配器需要构造和缓存,但每次重新构造它并不违法。这是一个在不更改实现的情况下无法转义的实现细节。创建的实际分配器类型是St13\u Rb\u tree\u nodeist4pairikiee(损坏的名称)。

在MyPool.h中(单例):

在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" )
#pragma一次
#包括“MyPool.h”
#pragma push_宏(“新”)
#未定义新
#包括
模板类fooStdAllocator;
//说明:
//专攻虚空
模板类fooStdAllocator
{
公众:
typedef void*指针;
typedef const void*const_指针;
typedef void value_type;
模板结构重新绑定{typedef fooStdAllocator other;};
};
模板类fooStdAllocator
{
公众:
//说明:
//Typedefs
类型定义T1值_类型;
typedef size_t size_type;
typedef ptrdiff t差异类型
#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;