删除双链接循环列表时出错

时间:2014-02-26 09:09:07

标签: c++ pointers delete-operator

我需要一个精心设计的双链接循环列表,因为我没有std我在下面构建了这个类。问题是当退出程序或完全删除CycleList时,我收到一个错误:访问冲突读取位置0xfeeeff22。 (MVS 2010)

有趣的是,当我调试时,一切似乎都被正确删除了。 (并且析构函数中的那3个cout完美打印......)。

有什么想法吗?

class CycleList{
public:

struct Node{
    static int s_size;
    static int e_size;
    IwPoint3d P;
    IwVector3d N;
    Node* next;
    Node* prev;

    Node(IwPoint3d _P, IwVector3d _N){
        P = _P;
        N = _N;
        next = this;
        prev = this;
        ++Node::s_size;
    }

    Node(IwPoint3d _P, IwVector3d _N, Node* _prev, Node* _next){
        P = _P;
        N = _N;
        prev = _prev;
        next = _next;
        prev->next = this;
        next->prev = this;
        ++Node::s_size;
    }

    ~Node(){
        prev->next = next;
        next->prev = prev;
        --Node::s_size;
    }
private:
    Node(const Node& rhs){} //copy forbidden
    Node operator=(const Node&){}
};

Node* current;
int size;

CycleList(IwPoint3d P, IwVector3d N){
    current = new Node(P,N);
    size = 1;
}

~CycleList(){
    while(!empty()){
        delete current->next;
    }
    cout << "I'm here" << endl;
    delete current;
    cout << "and here.." << endl;
    size = 0;
    cout << "and even here..." << endl;
}

bool empty() const{
    return current == current->next;
}

void insert_front(IwPoint3d P, IwVector3d N){
    new Node(P,N,current,current->next);
    ++size; 
}

void insert_back(IwPoint3d P, IwVector3d N){
    new Node(P, N,current->prev,current);
    ++size;
}

void delete_front(){
    if(!empty()){
        delete current->next;
        --size;
    }
}
void delete_back(){
    if (!empty()){
        delete current->prev;
        --size;
    }
}

IwPoint3d &front(){
    return current->next->P;
}

IwPoint3d &back(){
    return current->prev->P; 
}

void print(){
    for (int i = 0; i < size; ++i){
        cout << '(' << current->P.x << ", " << current->P.y << ", " << current->P.z << ')' << endl;
        current = current->next;
    }
}
};

好的,我找到了。我有一个这个CycleList的std :: List,它们通过复制得到它们,然后我删除了它们,然后在程序结束时删除这个列表可能跟随指针不再指向任何地方......

我在函数的末尾有类似崩溃的东西:

CycleList initial_front(hex1_p,hex1_n);
initial_front.print();

list<CycleList> Fronts;

Fronts.push_back(initial_front);

while (Fronts.size() > 0){
    CycleList current_front = Fronts.front();
    Fronts.pop_front();
    current_front.print();
}

但这样的事情正在发挥作用:

CycleList initial_front(hex1_p,hex1_n);
initial_front.print();

list<CycleList*> Fronts;

Fronts.push_back(&initial_front);

while (Fronts.size() > 0){
    CycleList* current_front = Fronts.front();
    Fronts.pop_front();
    current_front->print();
}

如果你有最好的方法,我会很高兴知道它。

1 个答案:

答案 0 :(得分:1)

初看起来,如果你没有推进当前的话,这似乎是免费的。

while(!empty()){
    delete current->next;
}