C++ 中的内存问题 - 未初始化读取:读取寄存器 eax
Memory Issue in C++ - UNINITIALIZED READ: reading register eax
为我正在处理的这个模板化程序声明默认构造函数后:
template<typename T>
Set<T>::Set()
: size(0), capacity(8) {
//allocate new array
items = new T[capacity];
}
我有一个相对不起眼的函数contains
,用于测试items
是否包含其中的特定项目。
template<typename T>
bool Set<T>::contains(const T& item) const {
for (int i = 0; i < size; i++) {
if (this->items[i] == item)
return true;
}
return false;
}
当我在某些位置调用它时它工作正常,例如这个函数读取 items
并且只在没有其他副本(我们的分配规范的一部分)时添加一个项目:
template<typename T>
void Set<T>::add(const T& item) {
if (this->contains(item) == 0) {
grow();
items[size++] = item;
}
}
但是当我试图重载运算符 ==
时调用它时,当我通过 DRMemory
运行 时,我在标题中得到了错误
template<typename T>
bool Set<T>::operator==(const Set<T>& other) const {
int count = 0;
for (int i = 0; i < size; i++) {
if (this->contains(other.items[i])) {
count++;
}
}
if (count == size)
return true;
return false;
}
for (int i = 0; i < size; i++) {
if (this->contains(other.items[i])) {
count++;
}
}
size
应该是 other.size
。否则循环中的other.items[i]
可能越界if size > other.size
.
同样在后面的检查中size
也需要是other.size
。
另一方面,您无论如何都需要为 size == other.size
添加一个测试,以确保这些集合确实相等。如果你把它放在开头,那么后面使用 size
还是 other.size
都没有关系。
顺便说一句。不要使用 count
来计算相同的元素,您可以在一个 .contains
失败时立即 return false
。
为我正在处理的这个模板化程序声明默认构造函数后:
template<typename T>
Set<T>::Set()
: size(0), capacity(8) {
//allocate new array
items = new T[capacity];
}
我有一个相对不起眼的函数contains
,用于测试items
是否包含其中的特定项目。
template<typename T>
bool Set<T>::contains(const T& item) const {
for (int i = 0; i < size; i++) {
if (this->items[i] == item)
return true;
}
return false;
}
当我在某些位置调用它时它工作正常,例如这个函数读取 items
并且只在没有其他副本(我们的分配规范的一部分)时添加一个项目:
template<typename T>
void Set<T>::add(const T& item) {
if (this->contains(item) == 0) {
grow();
items[size++] = item;
}
}
但是当我试图重载运算符 ==
时调用它时,当我通过 DRMemory
template<typename T>
bool Set<T>::operator==(const Set<T>& other) const {
int count = 0;
for (int i = 0; i < size; i++) {
if (this->contains(other.items[i])) {
count++;
}
}
if (count == size)
return true;
return false;
}
for (int i = 0; i < size; i++) {
if (this->contains(other.items[i])) {
count++;
}
}
size
应该是 other.size
。否则循环中的other.items[i]
可能越界if size > other.size
.
同样在后面的检查中size
也需要是other.size
。
另一方面,您无论如何都需要为 size == other.size
添加一个测试,以确保这些集合确实相等。如果你把它放在开头,那么后面使用 size
还是 other.size
都没有关系。
顺便说一句。不要使用 count
来计算相同的元素,您可以在一个 .contains
失败时立即 return false
。