首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么临时对象在作用域结束时被销毁后c++程序崩溃?

为什么临时对象在作用域结束时被销毁后c++程序崩溃?
EN

Stack Overflow用户
提问于 2015-01-17 06:59:49
回答 1查看 594关注 0票数 0

所以我有点困惑。在调用printList()之后尝试changeList()时,这段代码将失败。但是,当我删除析构函数时,代码不会崩溃。我的问题是,为什么?我了解到,在我这里的代码中,我通过值将对象传递给changeList,因此创建了一个临时对象作为参数的副本。对这个临时对象所做的任何更改都不会影响我传入的原始对象。那么,为什么程序会崩溃,就好像我在访问一个被破坏的对象一样?不应该在完成changeList之后销毁temp对象,然后printList应该只打印1×10而不是1×45。

代码语言:javascript
运行
复制
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
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-17 08:48:17

如果我假设正确,LinkedList的析构函数将销毁列表中的所有节点。我还假设复制构造函数对列表进行浅层复制。(如果没有显式实现复制构造函数,则这是默认的。)当您运行代码时会发生这样的情况:

代码语言:javascript
运行
复制
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函数中的引用参数来解决这个问题:

代码语言:javascript
运行
复制
void changeList(LinkedList &list)  // no copy
    list.append(new Node(45, nullptr));  
} // no destructor is called
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27997060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档