An exception is thrown, access violation reading location. I have overloaded all operators perfectly, and don't know the reason why is this happening. The loop was working fine in the tutorial, but it's not running on my system. Please help me, here's the code -
This is defined by me - 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_
And here is file containing main 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;
}*/
}
The value 0xdddddddd
is a well-known pattern of memory that have been passed to free
(or delete
). In other words, somewhere you're using memory that was allocated on the heap, but no longer is.
The problem is that your iterator
class copies the ring
object, but the ring
class doesn't follow the rules of three, five or zero.
A simple solution (and probably best) is to not copy at all, but to store a reference to the ring
object in the iterator
class:
template<class T>
class ring<T>::iterator
{
private:
int m_pos;
ring& m_ring; // Reference to a "ring"
...
};
To future-proof the ring
class I recommend that you take some time to study about the rules of three, five or zero.
I really recommend using std::vector
and follow the rule of zero.
User contributions licensed under CC BY-SA 3.0