gpt4 book ai didi

C++ 循环依赖解释

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:54 24 4
gpt4 key购买 nike

我有一个使用智能指针的循环依赖的基本示例。我一直在寻找一些解释,我知道如何解决这个问题,但我想知道幕后发生了什么。

这是代码:

#include <iostream>
#include <memory>
using namespace std;

class Child;
class Parent {
public:
shared_ptr<Child> child;
string name;
Parent(string n) : name(n) {
cout << "Parent: " << name << " constructor" << endl;
}
~Parent() {
cout << "Parent: " << name << " destructor" << endl;
}
};

class Child {
public:
shared_ptr<Parent> parent;
string name;
Child(string n) : name(n) {
cout << "Child: " << name << " constructor" << endl;
}
~Child() {
cout << "Child: " << name << " destructor" << endl;
}
};

int main(int argc, char** argv) {
shared_ptr<Parent> parent = make_shared<Parent>("Dad");//parent.use_count() => 1
shared_ptr<Child> child = make_shared<Child>("Child");//child.use_count() => 1
parent->child = child;//child.use_count() => 2
child->parent = parent;//parent.use_count() => 2
return 0;
}
//what happend at the end of the program?
//what happend when the shared_ptr destructors were called?
//was parent.use_count() decremented or is still 2?
//was child.use_count() decremented or is still 2?

输出:

Parent: Dad constructor
Child: Child constructor

我想知道的是以下内容

  • 调用 shared_ptr 析构函数时会发生什么?
  • parent.use_count() 是递减还是还是 2?
  • child.use_count() 是递减还是还是 2?

我想 shared_ptr 的析构函数代码是这样的:

~shared_ptr() {
//I want to know what it is happening right here
if (canDeletePointer(pointer)) {
delete pointer;
}
}

谢谢

最佳答案

  • 当 shared_ptr 析构函数被调用时,它会减少链接计数,如果它变为零,它会执行对象的析构函数并释放内存。
  • main() 函数结束后,两个共享指针被删除,因此它们的析构函数被执行,将儿子和父亲的计数从 2 减少到 1。

关于C++ 循环依赖解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36412454/

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