1

我写了一个模板类,它可以工作——但由于某种原因,我的动态分配存在问题。数组的初始长度:旧 2 新 4。它第一次工作(新点上的旧点(所以现在他的大小为 4)现在,新的大小为 8)但在下一轮 - 它在delete [] temp;with堆问题。有任何想法吗?谢谢

template <class T>
void Log<T>::Add(T item)
{
    // If array is full
    if(m_oldSize == m_oldCount)
    {
        // prepare array switch
        T* temp = m_old;

        // Point to new array
        m_old = m_new;
        m_oldSize = m_newSize;
        m_newSize *= ARRAY_MUL;
        m_newCount = DEFAULT_COUNT;

        //delete old
        delete [] temp;
        temp = NULL;

        //create new array
        m_new = new T[m_newSize];
    }

    // Add item and update new array
    m_old[m_oldCount++] = item;
    if(m_oldCount > FIRST_ROUND)
    {
        m_new[m_newCount++]= m_old[m_newCount];
        m_new[m_newCount++]= m_old[m_newCount];
    }
}
4

1 回答 1

0

由于这是作业,我刚刚创建了一个非优雅的解决方案,您应该能够找到陷阱并扩展它。

#include <iostream>

using namespace std;

struct foo
{
  foo(int h) : g(h) { }
  int g;
};

template <typename T>
class bar
{
public:
  bar() : curSize(2), curNo(0)
  {
    a = new T[curSize];
  }

  void Add(T item)
  {
    if (curNo == curSize) {
      curSize = 2 * curSize;
      T *newArray = new T[2*curSize];
      for (size_t i = 0 ; i != curNo; ++i) {
        newArray[i] = a[i];
      }
      delete[] a;
      a = newArray;

    }
    a[curNo] = item;
    ++curNo;

  }

  void print()
  {
    for (size_t i = 0 ; i != curNo; ++i) {
      cout << a[i]->g << endl;
    }
  }



private:

  size_t curSize;
  size_t curNo;
  T * a;
};


int main()
{
 foo *f1 = new foo(1);
 foo *f2 = new foo(2);
 foo *f3 = new foo(3);
 foo *f4 = new foo(4);
 bar<foo*> *g = new bar<foo*>();
 g->Add(f1);
 g->Add(f2);
 g->Add(f3);
 g->Add(f4);
 g->print();
 cout << "Add more and print" << endl;

 g->Add(f1);
 g->Add(f2);
 g->Add(f3);
 g->Add(f4);
 g->Add(f3);
 g->Add(f4);

 g->print();

}
于 2012-06-22T07:45:57.717 回答