迈克老狼

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

        标准库中allocator类把内存分配和对象构造分开,首先调用allocator类中的allocate(n), 分配n个T对象的raw空间,随后通过construct函数构造对象。反之,可以通过destroy函数释放对象,最后通过deallocate释放内存。

 

下面是allocator类分配内存以及构建对象时候,常用的几个方法:

allocator<T> a;

Defines an allocator object named a that can allocate memory or construct objects of type T.

a.allocate(n)

Allocates raw, unconstructed memory to hold n objects of type T.

a.deallocate(p, n)

Deallocates memory that held n objects of type T starting at address contained in the T* pointer named p. It is the user's responsibility to run destroy on any objects that were constructed in this memory before calling deallocate.

a.construct(p, t)

Constructs a new element in the memory pointed to by the T* pointer p. The copy constructor of type T is run to initialize the object from t.

a.destroy(p)

Runs the destructor on the object pointed to by the T* pointer p.

 uninitialized_copy(b, e, b2)

Copies elements from the input range denoted by iterators b and e into unconstructed, raw memory beginning at iterator b2. The function constructs elements in the destination, rather than assigning them. The destination denoted by b2 is assumed large enough to hold a copy of the elements in the input range.

 uninitialized_fill(b, e, t)

Initializes objects in the range denoted by iterators b and e as a copy of t. The range is assumed to be unconstructed, raw memory. The objects are constructed using the copy constructor.

 uninitialized_fill_n(b, e, t, n)

Initializes at most an integral number n objects in the range denoted by iterators b and e as a copy of t. The range is assumed to be at least n elements in size. The objects are constructed using the copy constructor.

 下面是使用allocator类编写的简单的myVector,是标准库中vector的简化版本:

 

Code

 

 

posted on 2009-11-18 09:57  迈克老狼  阅读(520)  评论(0编辑  收藏  举报