operator = on指针可能导致mac上的分段错误

时间:2016-11-04 16:48:40

标签: c++ macos terminal segmentation-fault operator-overloading

我试图编写一个带有链表的类Set来存储整数。在我的Mac终端上编译并运行之后,这就是输出:

[]
[10]
[10, 20]
[10, 20]
[10, 20, 30]

但我期待看到以下输出:

#include <iostream>
using namespace std;

class Node {
  public:
    int value;
    Node* next;
    Node(int n, Node* ptr = NULL) : value(n), next(ptr) {}
};

class Set {
  Node* head;
  friend ostream& operator<<(ostream&, const Set&);
  public:
    Set() : head(NULL) {}
    Set(const Set& another){ *this = another; }
    ~Set();
    Set& operator+=(const int&);
    Set& operator=(const Set&);
};

int main() {
    int num1 = 10;
    int num2 = 20;
    int num3 = 30;
    Set set1;
    cout << set1;
    Set* set2;
    set1 += num1;
    cout << set1;
    set1 += num2;
    cout << set1;
    set2 = new Set(set1);
    cout << *set2;
    *set2 += num3;
    cout << *set2;
    delete set2;
    return 0;
}

Set::~Set() {
    Node* current = head;
    while (current != NULL) {
        Node* temp = current;
        current = current->next;
        delete temp;
    }
}

Set& Set::operator+=(const int& aNum) {
    if (head == NULL) {
        head = new Node(aNum);
        return *this;
    }
    Node* previous = head;
    Node* current = head->next;
    while (current != NULL) {
        previous = current;
        current = current->next;
    }
    previous->next = new Node(aNum);
    return *this;
}

Set& Set::operator=(const Set& another) {
    if (this != &another) {
        Node* current = head;
        while (current != NULL) {
            Node* temp = current;
            current = current->next;
            delete temp;
        }
        Node* anotherCurrent = another.head;
        while (anotherCurrent != NULL) {
            *this += anotherCurrent->value;
            anotherCurrent = anotherCurrent->next;
        }
    }
    return *this;
}

ostream& operator<<(ostream& os, const Set& s) {
    os << "[";
    for (Node* p = s.head; p != NULL; p = p->next) {
        os << p->value;
        if (p->next != NULL)
            os << ", ";
    }
    os << "]" << endl;
    return os;
}

我想知道我的operator =函数是否有问题,还是我不能使用带有指针的operator =函数?如果是这样,我该如何纠正问题,以便程序按预期输出?我非常感谢你的帮助。提前谢谢!

iframe

1 个答案:

答案 0 :(得分:3)

在复制之前删除之前的列表时,您必须将head设置为NULL,否则+=运算符将使用head并且当前未分配但不是NULL Set& Set::operator=(const Set& another) { if (this != &another) { Node* current = head; while (current != NULL) { Node* temp = current; current = current->next; delete temp; } head = NULL; // <============== code to add Node* anotherCurrent = another.head; while (anotherCurrent != NULL) { *this += anotherCurrent->value; anotherCurrent = anotherCurrent->next; } } return *this;

console.log(a)

BTW一个非常有趣的设计模式,必须阅读:copy-and-swap idiom