自己的矢量误差

Own vector error

本文关键字:误差 自己的      更新时间:2023-10-16

我正在尝试创建自己的向量,我在开始时,编译 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];.
如果我定义X类的v1, v2, v3值,例如 X() : v1(0), v2(0), v3(0) { },程序可以正常工作。
如果我改变类型,例如,intVector,他可以完美地工作。
如果把X类放在std::vector,也可以正常工作。

其他意见也接受。

有人可以帮我吗?

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

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

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

  • clear错误地调用delete(导致崩溃和损坏)(您应该将数组的单个new与数组的单个delete相匹配。 不要循环访问元素。
  • add 写入超过数组末尾(导致崩溃和损坏)
  • 添加不是异常安全的

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

发生缓冲区溢出。

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

然后分配给 temp 数组,但在位置 temp[1] 中,这不是一个有效的位置,因为您的数组只有 1 个元素。这是未定义的行为,在这一点上,您的程序可以自由地继续,无论它选择什么。在这种情况下,它似乎无限循环。

// 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.