free():在重新分配或分配内存时无效的下一个大小(快)?

时间:2017-10-04 07:11:33

标签: c++ dynamic-allocation

我一直没有得到这个错误():当我分配或释放内存时,下一个大小(快)无效。我目前正在使用emacs而我根本不熟悉它的调试器,非常感谢任何帮助。

这是我的构造函数,析构函数,非默认const和赋值运算符,我正在使用

T *data;

`//default constructor                                                                    
template <class T> deque <T> :: deque()
{
   numCapacity = 0;
   data = NULL;
}`

//non default constructor                                                                            
template <class T> deque <T> :: deque(int capacity) throw (const char *)
{
   if (capacity == 0)
   {
      numCapacity = 0;
      data = NULL;;
      return;
   }
   try
   {
      data = new T[capacity];
   }
   catch(std::bad_alloc)
   {
      throw "ERROR: Unable to allocate a new buffer for deque";
   }
   numCapacity = capacity;
}
    //copy                                                                                               
template <class T> deque <T> :: deque(const deque<T> & rhs) throw (const char *)
{
   if (rhs.numCapacity == 0)
   {
      numCapacity = 0;
      data = NULL;
      return;
   }
   try
   {
      data = new T[rhs.numCapacity];
   }
   catch (std::bad_alloc)
   {
      throw "ERROR: unable to allocate buffer";
   }
   numCapacity = rhs.numCapacity;
   for (int i = 0; i < numCapacity; i++)
      data[i] = rhs.data[i];
}

//destructor
~deque()
{
     delete [] data;
}

//赋值运算符

//assignment operator                                                                                            
template <class T> deque<T> & deque<T> :: operator = (const deque<T> & rhs) throw (const char *)
{
   T *temp;
   int newSize = 0;

   if (rhs.numCapacity == numCapacity)
   {
      newSize = rhs.numCapacity + 1;
   }
   else if (rhs.numCapacity > numCapacity)
   {
      newSize = rhs.numCapacity;
   }
   else
   {
       for (int i = 0; i < newSize; i++)
          temp[i] = rhs.data[i];
       data = temp;
       numCapacity = newSize;
       return *this;
   }
 try
      {
         temp = new T[newSize];
      }
      catch(std::bad_alloc)
      {
         throw "ERROR: Unable to allocate a new buffer for deque";
      }

   for (int i = 0; i < newSize; i++)
      temp[i] = rhs.data[i];
   data = temp;
   numCapacity = newSize;
   return *this;
}

0 个答案:

没有答案