自定义向量类的解构函数

时间:2014-02-09 00:42:19

标签: c++

双重免费或损坏(快速顶部)错误。

我正在从头开始构建vector类,并与解构器混淆。

班级是:

template <class T>
class Vector
{
public:
   typedef T * iterator; //pointer to type T

   Vector();                              
   ~Vector();                       

   void reserve(unsigned int capacity); 
   void resize(unsigned int size);      

private:
   unsigned int my_size;
   unsigned int my_capacity;
   T * buffer;
};

template <class T>
Vector<T>::Vector()
{
my_size = 0;
my_capacity = 0;
buffer = 0;
}

template <class T>
Vector<T>::~Vector(){
    delete [] buffer;
    my_size = my_capacity = 0;
}

template <class T>
void Vector<T>::reserve(unsigned int new_capacity){
    int * new_buffer = new T[new_capacity];
    for(int i=0; i<my_size;i++){
        new_buffer[i] = buffer[i];
    }
    my_size += new_capacity;
    my_capacity += new_capacity;
    buffer = new_buffer;
    delete new_buffer;
}

template <class T>
void Vector<T>::resize(unsigned int new_size){
   //if new_size < size, change size.
   if(new_size < size) 
   {
       size = new_size;
   } else {
       if(new_size > my_capacity){ //increase capacity for larget size
           while(my_capacity < new_size){
               reserve(my_capacity+5);
           }
       }
       for(int i = my_size; i < new_size; i++){
           buffer[i] = T();
       }
       my_size = new_size;
   }
}

致电代码:

int main()
{  
   Vector<int> v;
   v.reserve(2);
   assert(v.capacity() == 2);
   cout << "SUCCESSFUL!!!\n"; 
}

我获得了成功的输出,但是当调用解构器时,我收到了我认为的错误。

1 个答案:

答案 0 :(得分:0)

由于多种原因,您的保留功能不正确。而是在buffer = new_buffer之前移动该函数的最后一行,并将其更改为delete [] buffer。在为新数据分配之前,您需要删除向量中的内容。它的编写方式是,您正在分配一个新缓冲区(丢失旧缓冲区的跟踪),然后从新缓冲区中删除所有数据。因此,当解构器命中时,您将删除指向任何内容的指针。