gpt4 book ai didi

c++ - 带有 smart_ptr 和 weak_ptr 的循环缓冲区?

转载 作者:太空宇宙 更新时间:2023-11-04 14:33:53 25 4
gpt4 key购买 nike

我找不到一个完整的例子来说明如何消除 shared_ptr 之间的强循环引用。

问题是如何使用 weak_ptr 来“关闭”通用元素链并使用 weak_ptr 访问“下一个”元素。

谢谢。

编辑:

例如,假设有 Element e1, e2, e3;,其中包含指向下一个元素的指针。在 C 中我们做

e1->Next = e2;
e2->Next = e3;
e3->Next = e1;

...我们可以做 e1->Next->Next->Next->Next->Next 等等

在使用 shared_ptr 的 C++ 中,我们不能执行最后的 ->Next = e1,因为循环引用和析构函数不会释放所有 Element .

我们需要一个 weak_ptr :但是什么策略可以得到相同的结果呢?

最佳答案

好的,我找到了解决方案。

当我需要从链的last 访问到first 元素(对象、结构或typedef_data)时,只需使用weak_prt使用 lock() (也许使用 expired() 来检查 poiter 是否仍然存在...)

例子:

 std::weak_ptr<int> gw;

void f()
{
if (auto spt = gw.lock()) { // Has to be copied into a shared_ptr before usage
std::cout << *spt << "\n";
}
else {
std::cout << "gw is expired\n";
}
}

int main() {

{ //into the scope
auto sp = std::make_shared<int>(42);
gw = sp;

f();
}
// out of the scope
f();
}

因此,输出将是:

42
gw is expired

expired()在本例中没有使用,但应该在lock()lock()的返回值之前使用< strong>必须始终选中。

关于c++ - 带有 smart_ptr 和 weak_ptr 的循环缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39211218/

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