C++析构函数崩溃程序

C++ destructor crashing program

我花了几个小时试图找出我的程序运行异常的原因,但我还没有弄清楚。

从未调用复制构造函数和赋值运算符。这要么意味着这不是 3 问题的规则,要么我错误地声明了它们,因此调用了默认值。该错误提到了有关有效堆指针块的内容,也许我错误地使用了 'new' 关键字?

如果需要更多信息来帮助我,请告诉我,谢谢。

主要:

#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;
}

戒指模板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_;
}

刚弄明白,我正在删除 't_',它不能保证指向分配块的开头。所以我不得不删除 begin_ 而不是!