我的代码当前设置的方式,我觉得我必须在分段错误和指向临时对象的指针之间做出选择。代码如下:
#include <memory>
#include <cstddef>
#include <iostream>
template <typename T> class Node;
template <typename T> class List {
public:
typedef std::size_t size_type;
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
class iterator {
public:
iterator() {
isNull = true;
}
iterator(const T val) {
isNull = false;
data = val;
prev = this;
next = &iterator(); #PROBLEMATIC LINE
}
iterator operator++() {
if(this->next->isNull)
return iterator();
iterator old_it = *this;
this->prev = &old_it;
this->next = this->next->next;
this->data = this->next->data;
return *this;
}
T& operator*() {
return data;
}
iterator* next;
iterator* prev;
T data;
bool isNull;
};
List() {
_begin = iterator();
_end = _begin;
}
List(size_type n, T val) {
_begin = iterator(val);
_end = *(_begin.next);
_end.prev = &_begin;
}
void push_back(T val) {
iterator temp = iterator();
_end.data = val;
_end.next = &temp;
temp.prev = &_end;
_end = temp;
}
iterator begin() {return _begin;}
iterator end() {return _end;}
private:
iterator _begin;
iterator _end;
};
int main() {
List<int> derp= List<int>(3,3);
List<int>::iterator i = derp.begin();
std::cout << *i;
derp.push_back(4);
std::cout << i.data;
++i;
std::cout << *i;
}
以上采用临时变量的地址。当我将有问题的行从
next = &iterator();
到
*next = iterator();
代码出现分段错误,但我不知道为什么。任何帮助,将不胜感激。以及您可能碰巧注意到的代码中的任何严重缺陷。