我发现了几个相关的问题,但是我找不到关于这种情况如何发生的解释。
我有以下代码,比可能产生循环shared_ptr
参考问题的版本落后一步。(返回前添加b.other = a;
会导致问题)
为了更好的说明,我在重要的行上添加了注释,以指示此时的程序状态。
#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
和b
的破坏顺序相反。我看到以下输出。
Constructed a
Constructed b
Destructed a
Destructed b
当程序返回到上面时会发生什么?(我希望了解这一点有助于理解循环依赖问题)
析构函数体被执行之前,成员被销毁(构造函数行为的相反。)
因此,a
中的main
被破坏时,a
的共享指针计数达到零first,然后调用托管的Foo
的析构函数,first将消息置于优先位置Destructed a
,并且then other
被销毁。