gpt4 book ai didi

c++ - operator= on pointers 可能导致 mac 上的段错误

转载 作者:行者123 更新时间:2023-11-27 23:59:09 25 4
gpt4 key购买 nike

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

[]
[10]
[10, 20]
Segmentation fault: 11

但我期待看到以下输出:

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

我想知道是我的 operator= 函数有问题,还是我不能将 operator= 函数与指针一起使用?如果是这样,我应该如何更正问题以使程序按预期输出?非常感谢您的帮助。提前致谢!

#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;
}

最佳答案

在复制之前删除以前的列表时,必须将 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;

顺便说一句,一个非常有趣的设计模式,必读:copy-and-swap idiom

关于c++ - operator= on pointers 可能导致 mac 上的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40427912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com