gpt4 book ai didi

c++ - 递归列表 : Everything calling destructor

转载 作者:行者123 更新时间:2023-11-28 04:41:02 27 4
gpt4 key购买 nike

所以我正在尝试制作一个递归链表。它看起来有点像这样:

class List  
{ int cur; //For now
List* nxt;

public:
List()
{cur = nullptr; nxt = nullptr;}
~List()
{std::cout << "Destroyed\n";}

...

现在我有一个函数缺点,

List cons(const int &a)
{ if(cur == nullptr)
{ cur = new int;
*cur = a;
}
else
{ List* x = new List;
x->cur = new int;
*(x->cur) = *cur;
x->nxt = nxt;
*cur = a;
nxt = x;
}
return *this;
}

还有一个运算符(operator),

std::ostream& operator<<(std::ostream& out, const List &b)
{ out << "Output\n";
return out;
}

我在 main 中使用这段代码来驱动它:

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

我的问题是,
a、为什么在成员函数内部调用析构函数,
b, 为什么它在 const 引用上调用析构函数,
c,析构函数到底是怎么工作的,我该如何阻止我的析构函数不断地自杀?

干杯。

最佳答案

函数 List cons(const int &a) 返回 *this 的拷贝。这会产生一堆临时 List 对象。

您看到的析构函数调用是针对每次调用 cons 返回的拷贝。

提示:请改用 List& cons(int a)

关于c++ - 递归列表 : Everything calling destructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50186576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com