我试图使用动态内存分配创建一个非常基本的链接列表。您可以添加元素并遍历该列表。但是在编写程序的析构函数时似乎遇到了问题(出现分段错误)。
我取而代之的是从析构函数中获取代码,然后将其放入一个名为purge()
的成员函数中,该函数没有产生任何错误。这是为什么?
我班上有什么根本上的问题吗?
#include <iostream>
struct LList
{
LList *p , *s;
int data;
LList (LList *prev , LList *succ, int n) : p{prev} , s{succ} , data{n}{}
~LList()
{
auto start = this;
while (start->p ) start = start->p;
while(1)
{
auto temp = start;
start = start->s;
delete temp;
if (start == nullptr) break;
}
std::cout << "Destruted!";
}
void traverse() const
{
auto start = this;
while (start->p != nullptr)start = start->p;
while (1)
{
std::cout << start->data;
if (start->s == nullptr) break;
else start = start->s;
}
}
};
int main()
{
LList *natural = new LList{nullptr , nullptr , 1};
natural = new LList{natural, nullptr , 2};
natural->p->s = natural;
natural = new LList{natural, nullptr , 5};
natural->p->s = natural;
natural->traverse();
std::cout << natural->data;
natural->~LList();
}
带有清除版本:
#include <iostream>
struct LList
{
....
void purge()
{
auto start = this;
while (start->p ) start = start->p;
while(1)
{
auto temp = start;
start = start->s;
delete temp;
if (start == nullptr) break;
}
std::cout << "Destruted!";
}
void traverse() const
{
auto start = this;
....
int main()
{
...
natural->purge();
}
p.s:甚至吹扫都可以做到吗?我仍然可以去:
natural->purge();
std::cout << natural->data;
}
最后,它将输出125Disrupted!5