逛奔的蜗牛

我不聪明,但我会很努力

   ::  :: 新随笔 ::  ::  :: 管理 ::
template<typename T> class Vector {
public:
        Vector() :
                elements(
0), first_free(0), end(0) {
        }

        
void push_back(const T &);
        
//.

private:
        
static std::allocator<T> alloc; // Object to get raw memory.
        void reallocate(); // Get more space and copy existing elements.
        T *elements; // Pointer to first element in the array.
        T *first_free; // Pointer to first free element in the array(no structed).
        T *end; // Pointer to one past the end of the array.
};

template
<typename T> void Vector<T>::push_back(const T &t) {
        
// Are we out of range ?
        if (first_free == end)
                
// Get more space and copy the existing elements to it
                reallocate();
        alloc.construct(first_free, t);
        
++first_free;
}

template
<typename T> void Vector<T>::reallocate() {
        
// Compute size of current array and
        
// allocate space for twice as many elements
        std::ptrdiff_t size = first_free - elements;
        std::ptrdiff_t newcapacity 
= 2 * max(size, 1);
        
// Allocate space to hold newcapacity number of elements of type T
        T *newelements = alloc.allocate(newcapacity);

        
// Construct copies of the existing elements in new space
        uninitialized_copy(elements, first_free, newelements);
        
// Destroy the old elements in reverse order
        for (T *= first_free; p != elements;) {
                alloc.destroy(
--p);
        }

        
// deallocate cannot be called on a 0 pointer
        if (elements) {
                alloc.deallocate(elements, end 
- elements);
        }

        
// Make our data structure pointer to the new elements
        elements = newelements;
        first_free 
= elements + size;
        end 
= elements + newcapacity;
}


uninitialized_copy 调用标准copy算法的特殊版本. 这个版本希望目的地是未构造的原始内存,它在目的地复制构造每个元素, 而不是将输入范围的元素赋值给目的地(复制时,左操作数是已经存在,但在无默认构造函数的情况下肯定不行,所以用的是复制构造).
for循环对旧数组中每个对象调用allocator的destroy()函数运行 T 类型的虚构函数来释放旧元素所用的任何资源.
一旦复制和撤销了旧元素,就释放原来数组所用空间. 在调用deallocate之前,必须检查elements是否实际指向一个数组.


posted on 2008-03-15 02:35 逛奔的蜗牛 阅读(342) 评论(0)  编辑 收藏 引用 所属分类: C/C++

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理