首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++析构函数崩溃程序

C++析构函数崩溃程序
EN

Stack Overflow用户
提问于 2016-11-05 21:41:37
回答 1查看 433关注 0票数 0

我花了几个小时试图找出为什么我的程序是错误的,但我还没有弄清楚。

从来不调用复制构造函数和赋值运算符。这要么意味着这不是第三个问题的规则,要么是我错误地声明了它们,因此调用了缺省值。这个错误提到了一个有效的堆指针块,也许我不正确地使用了'new‘关键字?

如果还需要更多的红外线帮助,请告诉我,谢谢。

Main:

代码语言:javascript
复制
#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;
}

环模板类:

代码语言:javascript
复制
#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_;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-05 21:45:15

刚算出来,我就删除了“t_”,这并不保证会指向分配块的开始。所以我不得不删除begin_!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40443501

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档