自己的矢量错误

时间:2015-04-27 17:12:09

标签: c++

我正在尝试创建自己的向量,我在开头,当编译e执行代码时,我得到“程序没有响应”。这是代码:

struct X
{
  X(){};
  ~X(){};
  int v1, v2, v3;
};

template<typename T>
class Vector
{
  public:
    // constructors
    Vector();
    Vector(unsigned s);
    virtual ~Vector();

    // overloaded operators
    T operator[](unsigned index);

    // others
    void clear();
    void add(T value);
    unsigned getSize();
    bool isEmpty();

  private:
    // pointer to first item of memory block
    T* first;
    unsigned size;
};

template<typename T>
Vector<T>::Vector()
{
  first = NULL;
  size = 0;
}

template<typename T>
Vector<T>::Vector(unsigned s)
{
  size = s;
  first = new T[s];
};

template<typename T>
Vector<T>::~Vector()
{
  clear();
}

template<typename T>
void Vector<T>::clear()
{
  for(unsigned i = size ; i > 0 ; i--)
    delete &first[i];

  first = NULL;
}

template<typename T>
void Vector<T>::add(T value)
{
    T* temp = new T[size + 1]; // error happens here

    // copy data to new location
    for(unsigned i = 0 ; i < size ; i++)
      temp[i] = first[i];

    // delete older data
    clear();

    // add the new value in last index
    temp[size + 1] = value;

    // update the pointer
    first = temp;

    size++;
}

template<typename T>
T Vector<T>::operator[](unsigned index)
{
  return first[index];
}

template<typename T>
unsigned Vector<T>::getSize()
{
  return size;
}

template<typename T>
bool Vector<T>::isEmpty()
{
   return first == NULL;
}

int main(int argc, char* args[])
{
  Vector<X> anything;

  X thing;

  anything.add(thing);
  anything.add(thing);
  anything.add(thing); // if remove this line, program work fine.
}

正如我评论的那样,T* temp = new T[size + 1];发生了错误 如果我定义v1, v2, v3X的值,例如X() : v1(0), v2(0), v3(0) { },该计划正常运作 如果我改变类型,例如Vector int,他的工作完美 如果将X类放在std::vector中,也可以正常工作。

其他评论也被接受。

有人能帮忙吗?

2 个答案:

答案 0 :(得分:2)

您对问题的描述非常模糊,但我可以指出您的代码存在问题:

  • 没有vector复制构造函数(导致双删除和崩溃)

  • 没有vector副本分配(导致双重删除和崩溃)

  • clear错误地调用了delete(导致崩溃和损坏)(您应该将单个new数组与单个delete数组匹配。 t循环元素。
  • add正在写入数组的末尾(导致崩溃和损坏)
  • 添加不是例外安全

你必须至少修复前四个。第三和第四可能是你挂起的原因。

答案 1 :(得分:1)

发生缓冲区溢出。

T* temp = new T[size + 1]; // When size is 0, you allocate 1 space.

然后分配给临时数组,但位于temp[1]位置,这不是有效位置,因为您的数组只有1个元素。这是undefined behavior,这一点,您的程序可以继续自由选择。在这种情况下,它似乎无限循环。

// add the new value in last index
temp[size + 1] = value; // When size is zero, your array is length '1', but
                        // you are accessing temp[1] which is outside the
                        // bounds of your allocated memory.
相关问题