自己的矢量误差
Own vector error
我正在尝试创建自己的向量,我在开始时,编译 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) { }
,程序可以正常工作。
如果我改变类型,例如,int
的Vector
,他可以完美地工作。
如果把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.
相关文章:
- 没有为自己的结构调用列表推回方法
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- C++从对象自己的类中删除对象
- 使用 std::optional,而不是自己的结构
- 子轴围绕父轴而不是他自己的轴旋转
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- C++ 如何为自己的迭代器类从迭代器转换为const_iterator?
- 重载 + 自己的类和 std::string 的运算符
- 类无法访问自己的私有静态 constexpr 方法 - Clang bug?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何访问模板参数自己的模板参数?
- 将矩阵乘以我自己的输入的向量
- 您应该在什么时候创建自己的异常类型
- 派生类是从基类继承 v 指针并仅使用它,还是也有自己的 v 指针?
- string1 == string2 和你自己的 for 循环比较有什么区别?
- 如何正确包含我自己的标头?
- 自己的自定义向量类. 内存重新分配
- 如何使用我构建的库,而不会从源代码出错,但不为我自己的项目编译?
- 自己的矢量误差