C++ `std::shared_ptr`循环依赖关系如何导致问题
我发现了几个相关的问题,但我找不到一个关于这是如何发生的解释 我有下面的代码,它比可以创建循环共享\u ptr引用问题的版本落后一步。 加上b.other=a;在返回之前导致问题 为了更好地澄清,我在重要的行上添加了注释,以指示程序在该点上的状态C++ `std::shared_ptr`循环依赖关系如何导致问题,c++,c++11,memory-management,smart-pointers,C++,C++11,Memory Management,Smart Pointers,我发现了几个相关的问题,但我找不到一个关于这是如何发生的解释 我有下面的代码,它比可以创建循环共享\u ptr引用问题的版本落后一步。 加上b.other=a;在返回之前导致问题 为了更好地澄清,我在重要的行上添加了注释,以指示程序在该点上的状态 #include <iostream> #include <memory> using namespace std; struct Foo { explicit Foo(char i) : id{i} { cout
#include <iostream>
#include <memory>
using namespace std;
struct Foo
{
explicit Foo(char i) : id{i} { cout << "Constructed " << id << endl; }
~Foo() { cout << "Destructed " << id << endl; }
shared_ptr<Foo> other = {};
char const id;
};
int main()
{
auto const a = make_shared<Foo>('a'); // a_use_count = 1, b_use_count = 0
auto const b = make_shared<Foo>('b'); // a_use_count = 1, b_use_count = 1
a->other = b; // a_use_count = 1, b_use_count = 2
return 0; // What happens now? Following is my "expectation" (which is wrong !)
// 1. destruct b => a_use_count = 1, b_use_count = 1
// 2. destruct a (in following order)
// 2.1 destruct a.other => b_use_count = 0 => show "Destructed b"
// 2.2 destruct a => a_use_count = 0 => show "Destructed a"
}
当程序返回到上面时,会发生什么?
我希望理解这一点将有助于理解循环依赖性问题在销毁成员之前执行析构函数体,与构造函数行为相反
因此,当主中的a被析构函数时,a的共享指针计数首先达到零,然后调用托管Foo的析构函数,首先触发消息destructed a,然后销毁另一个,这会导致在其托管Foo的析构函数中打印析构函数b。所示程序的情况并不复杂,但它与循环依赖性引起的基本问题基本无关,除了一种非常基本的方式。这是专门针对C++11的Q吗?@curiousguy这是关于C++11和更高版本的,因为std::shared_ptr以前不可用。谢谢,我忽略了明显的问题。我将再次考虑是否理解循环依赖性问题,是否接受您的答案或更新我的问题。@Sumudu如果您想用shared_ptr演示循环依赖性问题,那么您需要通过添加b->other=a来实际使依赖性循环。如果您在这种情况下遵循相同的分析,您将看到没有一个析构函数将执行,这表明内存泄漏。
Constructed a
Constructed b
Destructed a
Destructed b