我有一个使用智能指针的循环依赖的基本示例。 我一直在寻找一些解释,并且我知道如何解决这个问题,但我想知道幕后发生了什么。
这是代码:
#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/