模板运算符重载中的分段错误

时间:2017-03-28 19:58:01

标签: c++ templates operator-overloading

我目前正试图掌握C ++中的模板和运算符重载。我写了一个基本上是向量包装的类。我正在尝试将运算符重载添加到模板类中,以便我可以迭代列表,但是我一直在接收带有重载运算符的分段错误。

这是模板代码。

template <class T> class List {
private:
    std::list<T *> *objects;
    int count;
    uint currentIndex;
    typename std::list<T*>::iterator item_iter;

public:
    T *currentItem;
    T *get(int idx);
    void add(T *obj);
    void start();
    bool empty();
    void next();
    List<T>& operator++();

    List() {
        this->currentItem = NULL;
        this->currentIndex = 0;
        this->count = 0;
        this->objects = new std::list<T *>;
    }

    ~List() {
        delete this->objects;
    }
};

template <class T>
void List<T>::add(T *obj) {
    this->objects->push_back(obj);
}

template <class T>
T *List<T>::get(int idx) {
    if (idx < this->objects->size()) {
      typename std::list<T*>::iterator it = this->objects->begin();
      std::advance(it, idx);
      return *it;
    } else {
      return NULL;
    }
}

template <class T>
void List<T>::start() {
    this->currentIndex = 0;
    if (this->objects->size() > 0) {
      this->item_iter = this->objects->begin();
      this->currentItem = *(this->item_iter);
    } else {
      this->currentItem = NULL;
    }
}

template <class T>
void List<T>::next() {
     if (!this->empty() && (this->currentIndex == 0) && (this->currentItem == NULL)) {
      this->start();
    } else if (this->currentIndex < this->objects->size() - 1) {
      this->currentIndex++;
      std::advance(item_iter, 1);
      this->currentItem = *item_iter;
    } else {
      this->currentItem = NULL;
    }
}

template <class T>
bool List<T>::empty() {
    return !this->objects->size();
}

template <class T>
List<T>& List<T>::operator++() {
    // Note: We don't get this far
    this->next();
    return *this;
}

以下代码有效。

List<Item> *items = new List<Item>();
items->addItem(new Item(20));

for(items->start(); items->currentItem != NULL; items->next()) {
    // Can work with items->currentItem;
}

以下代码会导致分段错误。

List<Item> *items = new List<Item>();
items->addItem(new Item(20));

for(items->start(); items->currentItem != NULL; items++) {
    // Segmentation fault occurs before we get inside
}

1 个答案:

答案 0 :(得分:0)

@FrançoisAndrieux是对的。

我需要取消引用项目指针。

for(items.start(); items.currentItem != NULL; ++items) {
    // Can now use current item
}

我也改变了返回类型。

template <class T>
List<T> List<T>::operator++() {
    this->next();
    return *this;
}