Reputation: 131
I've spent a couple hours trying to figure out why my program is misbehaving and I haven't been able to figure it out yet.
The copy constructor and assignment operator are never called. This either means this isn't a rule of 3 problem, or I declared them incorrectly so the defaults are being called. The error mentions something about a valid heap pointer block, maybe I am using the 'new' keyword incorrectly?
Let me know if any more infmoratoin is required to help me out, thanks.
Main:
#include "Ring.h"
#include <iostream>
int main()
{
Ring<int> int_ring(3);
int_ring.Add(1);
int_ring.Add(2);
int_ring.Add(3);
int_ring.Add(4); // Will overwirte 1
for (int i = 0; i < int_ring.size(); i++) {
std::cout << int_ring.Get(i) << '\n';
}
return 0;
}
Ring template class:
#include <iostream>
#include <string>
template<class T>
class Ring
{
public:
Ring(int size);
Ring(const Ring &other);
~Ring();
T* begin();
T* end();
Ring& operator=(const Ring rhs);
void Add(T t);
T Get(int i);
int size();
private:
int size_;
T *t_;
T *begin_;
T *end_;
void MoveIt() {
t_++;
if (t_ == end_) { t_ = begin_; }
}
};
template<class T>
Ring<T>::Ring(int size) : size_(size), t_(new T[size_]), begin_(t_), end_(t_ + size_) {
}
template<class T>
Ring<T>::Ring(const Ring &other) : size_(other.size_), t_(new T[size_]), begin_(t_), end_(t_ + size_) {
std::cout << "Copy\n";
}
template<class T>
T* Ring<T>::begin() { return begin_; }
template<class T>
T* Ring<T>::end() { return end_; }
template<class T>
Ring<T>& Ring<T>::operator=(const Ring<T> rhs) {
std::cout << "=\n";
std::swap(rhs);
return *this;
}
template<class T>
void Ring<T>::Add(T t) {
(*t_) = t;
MoveIt();
}
template<class T>
T Ring<T>::Get(int i) {
return begin_[i];
}
template<class T>
int Ring<T>::size() {
return size_;
}
template<class T>
Ring<T>::~Ring() {
std::cout << "delete\n";
delete[] t_;
}
Upvotes: 0
Views: 525
Reputation: 131
Just figured it out, I was deleting 't_' which wasn't guaranteed to be pointing to the start of the allocated block. So I had to delete begin_ instead!
Upvotes: 2