C++循环依赖解释

标签 c++ smart-pointers circular-dependency

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

这是代码:

#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/

相关文章:

C++ 十进制数据类型

c++ - 深度优先搜索 (C++)

c# - 在 ASP.NET MVC 4 解决方案中配置编译时依赖注入(inject)的依赖倒置

c++ - 将所有权从 std::shared_ptr 转移到 std::unique_ptr

c++ - 将构造函数的参数复制到智能指针中

头文件中的 C++ 循环依赖

c# - 为什么 C# 中的命名空间允许循环依赖?

c++ - LibCurl Unicode 数据

c++ - 如何获取 QTableWidget 列的标签值

C++ 智能指针性能以及与简单包装指针的差异