std :: shared_ptr`循环依赖如何引起问题

问题描述 投票:0回答:1

我发现了几个相关的问题,但是我找不到关于这种情况如何发生的解释。

我有以下代码,比可能产生循环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"
}

但是,事情没有发生我所期望的。 ab的破坏顺序相反。我看到以下输出。

Constructed a
Constructed b
Destructed a
Destructed b

当程序返回到上面时会发生什么?(我希望了解这一点有助于理解循环依赖问题)

c++ c++11 memory-management smart-pointers
1个回答
1
投票

析构函数体被执行之前,成员被销毁(构造函数行为的相反。)

因此,a中的main被破坏时,a的共享指针计数达到零first,然后调用托管的Foo的析构函数,first将消息置于优先位置Destructed a,并且then other被销毁。

© www.soinside.com 2019 - 2024. All rights reserved.