gpt4 book ai didi

c++ - 普通引用而不是 weak_ptr 来打破循环依赖

转载 作者:行者123 更新时间:2023-11-30 03:22:25 26 4
gpt4 key购买 nike

看看 std::weak_ptr 我在几个地方看到它可以用来打破由于使用 std::shared_ptr 的循环依赖导致的内存泄漏>。例如,请参见这两个已接受的答案:[1] , [2] .

采用最后引用的答案,建议的修复是:

#include <memory>
#include <iostream>

struct B;
struct A {
std::shared_ptr<B> b;
~A() { std::cout << "~A()\n"; }
};

struct B {
std::weak_ptr<A> a;
~B() { std::cout << "~B()\n"; }
};

void useAnB() {
auto a = std::make_shared<A>();
auto b = std::make_shared<B>();
a->b = b;
b->a = a;
}

int main() {
useAnB();
std::cout << "Finished using A and B\n";
}

不过,这感觉有点矫枉过正,为什么不简单地使用引用呢?我知道在这个例子中 b->a 没有在构造函数中设置,所以引用不会真正削减它,所以我的问题是:

Is there a reason to use a std::weak_ptr instead of a reference if the point is to break circular dependency if we can set it in the constructor?

注意:我理解 std::weak_ptr 用于保存可以失效的引用的用处。我的问题只涉及当要点专门打破循环依赖时的有用性。

最佳答案

这是一个稍微修改过的函数:

void useAnB() {
std::shared_ptr<B> oops;
{
auto a = std::make_shared<A>();
auto b = std::make_shared<B>();
a->b = b;
b->a = a;
oops = b;
}
// use oops->a
}

如果 oops->a 是普通指针或引用,您怎么知道它不再引用有效对象?

关于c++ - 普通引用而不是 weak_ptr 来打破循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51152548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com