深入模板编程笔记四

template 
class my_vector {
public:
    T* array;
    unsigned size;
    unsigned block_size;
    
public:
    my_vector(unsigned bsz):
    array((T*)malloc(sizeof(T)*bsz)),size(0), block_size(bsz){}
    ~my_vector() {if (array) free(array);}
    
    void push_back(T const& elem) throw(std::runtime_error) {
        if (size == block_size) {//已有空间用完,申请更大空间
            block_size *= 2;
            T* new_array = (T*)realloc(array, block_size*sizeof(T));
            if (new_array!= NULL) array = new_array;
            else {
                //申请失败,内存耗尽
                free(array);
                array = NULL;
                throw std::runtime_error("out of memory.");
            }
        }
        array[size++] = elem;
    }
    
    T& operator[] (unsigned i) {return array[i];}
    const T& operator[] (unsigned i) const {return array[i];}
    unsigned get_mem_size() const {return block_size*sizeof(T);}
};
//这是一个用木板封装的容器

你可能感兴趣的:(生活)