为什么在这个空对象上迭代会导致核心转储?

发布于 2025-01-23 06:47:06 字数 1139 浏览 2 评论 0原文

我现在正在研究这个迭代程序,当我尝试在空列表上迭代时,我会遇到麻烦。这是感兴趣的守则:

// part A
DoublyLinkedList<int> myListOneNode;

myListOneNode.insertLast(42);
cout << "TestIterationTricky test #1, the next line should display 42" << endl;
stringstream ss;
//see if we can just iterator through one item.
for (auto i : myListOneNode) {
    cout << i << " ";
    ss << i << " ";
}
cout << endl;
checkTest("TestIterationTricky test #1", "42 ", ss.str()); // is ss equal to "42 " ?
ss.str("");
// part B
DoublyLinkedList<int> myListEmpty;
cout << "TestIterationTricky test #2, the next line shouldn't display anything" << endl;
//see if we can just iterator through one item.
for (auto i : myListEmpty) {
    cout << i << " ";
    ss << i << " ";
}
cout << endl;
checkTest("TestIterationTricky test #2", "", ss.str()); // is ss equal equal to "" ?
ss.str("");

此摘录中的A部分效果很好,没有错误。

但是,B部分导致分割故障。该程序在达到循环的定义后立即崩溃。

有什么想法吗?

I'm working on this iterating program right now, and I'm running into trouble when I try to iterate over an empty list. Here's the code of interest:

// part A
DoublyLinkedList<int> myListOneNode;

myListOneNode.insertLast(42);
cout << "TestIterationTricky test #1, the next line should display 42" << endl;
stringstream ss;
//see if we can just iterator through one item.
for (auto i : myListOneNode) {
    cout << i << " ";
    ss << i << " ";
}
cout << endl;
checkTest("TestIterationTricky test #1", "42 ", ss.str()); // is ss equal to "42 " ?
ss.str("");
// part B
DoublyLinkedList<int> myListEmpty;
cout << "TestIterationTricky test #2, the next line shouldn't display anything" << endl;
//see if we can just iterator through one item.
for (auto i : myListEmpty) {
    cout << i << " ";
    ss << i << " ";
}
cout << endl;
checkTest("TestIterationTricky test #2", "", ss.str()); // is ss equal equal to "" ?
ss.str("");

Part A in this excerpt works fine, no errors.

Part B, however, results in a segmentation fault. The program crashes as soon as it reaches the definition of the for loop.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文