所以我有点困惑。在调用printList()之后尝试changeList()时,这段代码将失败。但是,当我删除析构函数时,代码不会崩溃。我的问题是,为什么?我了解到,在我这里的代码中,我通过值将对象传递给changeList,因此创建了一个临时对象作为参数的副本。对这个临时对象所做的任何更改都不会影响我传入的原始对象。那么,为什么程序会崩溃,就好像我在访问一个被破坏的对象一样?不应该在完成changeList之后销毁temp对象,然后printList应该只打印1×10而不是1×45。
void printList(Node*);
void changeList(LinkedList);
int main(){
LinkedList list;
for (int i = 0; i < 10; i++)
list.append(new Node(i+1, nullptr));
changeList(list);
printList(list.getHead());
system("pause");
return 0;
}
void changeList(LinkedList list){
list.append(new Node(45, nullptr));
}
void printList(Node* head){
Node* temp = head;
if (temp != nullptr){
cout << temp->value << endl;
printList(temp->next);
}//end if
}发布于 2015-01-17 08:48:17
如果我假设正确,LinkedList的析构函数将销毁列表中的所有节点。我还假设复制构造函数对列表进行浅层复制。(如果没有显式实现复制构造函数,则这是默认的。)当您运行代码时会发生这样的情况:
void printList(Node*);
void changeList(LinkedList);
int main(){
LinkedList list; //first instance is created
for (int i = 0; i < 10; i++)
list.append(new Node(i+1, nullptr)); // nodes added to the first instance
changeList(list); // copy constructor called, second instance is
// created with the same set of node objects
printList(list.getHead()); // nodes does not exist any more because of
// the destructor called at the end of changeList
system("pause");
return 0;
}
void changeList(LinkedList list) // copy constructor called, second instance is created
list.append(new Node(45, nullptr)); // nodes added to the same chain of nodes
} // destructor is called, all the nodes are destroyed
void printList(Node* head){
Node* temp = head;
if (temp != nullptr){
cout << temp->value << endl;
printList(temp->next);
}//end if
}您可以通过接受changeList函数中的引用参数来解决这个问题:
void changeList(LinkedList &list) // no copy
list.append(new Node(45, nullptr));
} // no destructor is calledhttps://stackoverflow.com/questions/27997060
复制相似问题