C ++析构函数崩溃程序

时间:2016-11-05 21:41:38

标签: c++ destructor

我花了几个小时试图找出我的程序行为不端的原因,但我还没弄清楚。

Result of running program

永远不会调用复制构造函数和赋值运算符。这或者意味着这不是3问题的规则,或者我声明它们不正确所以默认被调用。错误提到有关有效堆指针块的内容,也许我错误地使用了'new'关键字?

让我知道是否需要更多的infmoratoin来帮助我,谢谢。

主:

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

响铃模板类:

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

1 个答案:

答案 0 :(得分:2)

刚想通了,我正在删除't_',这不能保证指向已分配块的开头。所以我不得不删除begin_而不是!

相关问题