C++的内存分配

来源:互联网 发布:阿里云服务器国际版 编辑:程序博客网 时间:2024/06/08 02:53

C++的内存分配有两种方法(分配和释放未构造的原始内存):

1)allocator类,2)new 和delete

第一种:

allocator类的定制算法:

allocator<T>a :定义分配类型为T的分配对象a;

a.allocate(n) : 分配T类型的n个空间,不调用类型的构造函数;

a.deallocate(p,n): 释放在T*的p指针处的n个对象所具有的内存空间,不用类型析构函数,在此这之前调用对象的析构函数是用户的责任 ;

a.construct(p,t) : 在T*的p指针处调用类型的复制构造函数用t初始化该对象;

a.destroy(p): 调用T*的p指针所指对象的析构函数;

uninitialized_copy(b,e,b2): 从迭代器b和e之间的元素复制构造到迭代器b2中;

uninitialzed_fill(b,e,t):

uninitialzed_fill_n(b,e,t,n):

下面用vector的内存分配策略来理解allocator类:

template<class T>class Vector {

public:

Vector():elements(0),first_free(0),end(0) {}

void push_back(const T&) ;

private:

static std::allocator<T>alloc ;

void reallocate() ;

T* elements ;

T* first_free ;

T* end ;

} ;

 

 

使用construct:

template<class T>

void Vector<T>::push_back(const T&)

{

if(first_free == end)

  reallocate() ;

alloc.construct(first_free,t) ;

++first_free ;
}

 

 

重新分配元素与复制元素:

template<class T>

void Vector<T>::reallocte()

{

  std::ptrdiff_t size = first_free-elements ;

  std::ptrdiff_t newcapacity = 2 * max(size,1) ;

  T* newelements = alloc.allocate(newcapacity) ;

  uninitialized_copy(elements,first_free,newelements) ;

  for(T* p = first_free ; p!= elements;)

   alloc.destroy(--p) ;

 if(elements)

   alloc.deallocate(elements,end-elements) ;

 

  elements = newelements ;

  first_free = newelements+size ;

  end = newelements+newcapacity ;
}

 

 

第二种:

new和delete会自动调用对象的构造函数和析构函数的;是运算符,可重载;