[英]Unhandled exception at 0x5E10F1C0 (ucrtbased.dll) in HW 5 Rational pt2.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC. occurred
[英]Exception thrown at 0x7933F3BE (ucrtbased.dll) in Making Classes Iterable.exe: 0xC0000005: Access violation reading location 0xDDDDDDDD. occurred
拋出異常,訪問沖突讀取位置。 我已經完美地重載了所有運算符,並且不知道發生這種情況的原因。 該循環在本教程中運行良好,但它沒有在我的系統上運行。 請幫助我,這是代碼 -
這是由我定義的 - ring.h
#pragma once
#ifndef RING_H_
#define RING_H_
#include<iostream>
using namespace std;
template<class T>
class ring
{
private:
int m_pos;
T* m_values;
int m_size;
public:
class iterator;
public:
ring(int size) : m_pos(0), m_size(size), m_values(NULL)
{
m_values = new T[size];
}
~ring()
{
delete[] m_values;
}
int size()
{
return m_size;
}
iterator begin()
{
return iterator(0, *this);
}
iterator end()
{
return iterator(m_size-1, *this);
}
void add(T value)
{
m_values[m_pos++] = value;
if (m_pos == m_size)
{
m_pos = 0;
}
}
T& get(int pos)
{
return m_values[pos];
}
};
template<class T>
class ring<T>::iterator
{
private:
int m_pos;
ring m_ring;
public:
iterator(int pos, ring &aRing): m_ring(aRing), m_pos(pos) {}
iterator& operator++(int)
{
m_pos++;
return *this;
}
T& operator*()
{
return m_ring.get(m_pos);
}
bool operator!=(const iterator& other) const
{
return m_pos != other.m_pos;
}
};
#endif //RING_H_
這是包含主要 function 的文件 - (source.cpp)
#include<iostream>
#include"ring.h"
using namespace std;
int main()
{
ring<string> textring(3);
textring.add("One");
textring.add("Two");
textring.add("Three");
for (ring<string>::iterator it = textring.begin(); it != textring.end(); it++)
{
cout << *it << endl;
}
cout << endl;
/*for (string value : textring)
{
cout << value << endl;
}*/
}
值0xdddddddd
是眾所周知的 memory 模式,已傳遞給free
(或delete
)。 換句話說,您在某處使用在堆上分配的 memory,但不再是。
問題是您的iterator
class復制了ring
object,但ring
class 不遵循三、五或零的規則。
一個簡單的解決方案(可能是最好的)是根本不復制,而是在iterator
class 中存儲對ring
object 的引用:
template<class T>
class ring<T>::iterator
{
private:
int m_pos;
ring& m_ring; // Reference to a "ring"
...
};
為了保證ring
class 的未來發展,我建議您花一些時間研究三、五或零的規則。
我真的建議使用std::vector
並遵循零規則。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.