在析构函数中避免对成员变量进行无限递归调用。可以使用智能指针或者手动管理内存来解决。下面是使用智能指针解决无限递归问题的示例代码:
#include
class MyClass {
public:
MyClass() = default;
~MyClass() = default;
private:
std::shared_ptr child;
//std::unique_ptr child; // 也可以使用unique_ptr
};
int main() {
std::shared_ptr parent = std::make_shared();
parent->child = std::make_shared();
parent->child->child = parent;
return 0;
}
在这个示例代码中,MyClass 类中有一个智能指针 child,它持有另一个 MyClass 对象的指针。在 main 函数中,我们创建了两个 MyClass 对象,parent 和 child,它们相互引用,即 parent->child->child = parent。如果没有智能指针来处理这种引用关系,就会导致析构函数中的无限递归调用,从而导致栈溢出等问题。而使用智能指针,它们会在 parent 和 child 没有被引用时自动销毁,避免了无限递归调用问题。
上一篇:避免下载文件