c++ - 自 vector 错误

标签 c++

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

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 与单个 匹配>删除数组。不要遍历元素。
  • add 写入数组末尾(导致崩溃和损坏)
  • 添加不是异常安全的

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

关于c++ - 自 vector 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29902003/

相关文章:

c++ - 没有用于初始化 std::lock_guard<std::mutex> 的匹配构造函数

c++ - 如何将 gcov 与 QMake 一起用于代码覆盖

C++ - 自动转换为 std::string

c++ - 磁盘上文件备份的键值对列表/映射

c++ - 双重比较(再次)

c++ - 重载 + 运算符的继承

c++ - 传递接口(interface)函数的函数指针

c++ - 我如何在 C/C++ 中接收原始的第 2 层数据包?

c++ - 连接到不同计算机上的 session DBus

c++ - 为什么这个程序是用 gcc 编译的,而不是用 g++ 编译的?