C++ 递归列表:调用析构函数的所有内容
所以我想做一个递归链表。看起来有点像这样:C++ 递归列表:调用析构函数的所有内容,c++,C++,所以我想做一个递归链表。看起来有点像这样: class List { int cur; //For now List* nxt; public: List() {cur = nullptr; nxt = nullptr;} ~List() {std::cout << "Destroyed\n";} ... 还有一个接线员 std::ostream& operator<<(std::ostrea
class List
{ int cur; //For now
List* nxt;
public:
List()
{cur = nullptr; nxt = nullptr;}
~List()
{std::cout << "Destroyed\n";}
...
还有一个接线员
std::ostream& operator<<(std::ostream& out, const List &b)
{ out << "Output\n";
return out;
}
我的问题是,,
a、 为什么它在成员函数中调用析构函数,
b、 为什么它要对常量引用调用析构函数,
还有c,析构函数到底是怎么工作的,我该如何阻止我的析构函数不断地自杀
干杯。函数列表conscont int&a返回*的一份副本。这将产生一组临时列表对象
您看到的析构函数调用是针对每次调用cons返回的副本的
提示:使用列表和内容a代替。Ahh。太好了,谢谢。我想接下来会是,我计划编写一个返回*nxt用于递归的体函数或尾函数。。。实现这一目标的方法是否也是列表&?例如,我设想我最终会实现如果head和tail返回一个引用,那么不会调用析构函数,也不会像调用head/tail所期望的那样删除任何内容。
std::ostream& operator<<(std::ostream& out, const List &b)
{ out << "Output\n";
return out;
}
int main()
{ List a;
std::cout << "Cons\n";
a.cons(3);
std::cout << "Cons\n";
a.cons(2);
std::cout << "Cons\n";
a.cons(1);
std::cout << a;
}
Cons
Destroyed
Cons
Destroyed
Cons
Destroyed
Out
Destroyed
Destroyed