gpt4 book ai didi

c++ - shared_ptr中weak_ptr的作用

转载 作者:太空狗 更新时间:2023-10-29 20:40:09 25 4
gpt4 key购买 nike

我了解 shared_ptr 的工作原理,除了 weak_ptr 的作用。我知道当引用计数不为零时它会检测循环引用,但除此之外我不明白它是如何做到这一点的。它有什么作用?

最佳答案

另请参阅:When is std::weak_ptr useful?为什么和How does weak_ptr work?如何。

我将提供一个示例来说明我是如何使用它的,尽管我编写的示例代码有点令人费解,请耐心等待:

#include <vector>
#include <memory>
#include <ostream>

int main()
{
// Fill container with values 1-50. This container OWNS these values.
std::vector<std::shared_ptr<int>> owning_container;
for(int i = 1; i <= 50; ++i)
{
owning_container.emplace_back(std::make_shared<int>(i));
}

// Create a sepearate container that references all owned values that are multiples of 5.
std::vector<std::weak_ptr<int>> referencing_container;
for(std::shared_ptr<int> const& i : owning_container)
{
if((*i) % 5 == 0)
{
// Make weak_ptr that references shared_ptr
referencing_container.emplace_back(i);
}
}

// Go through the owned values and delete all that are multiples of 10.
for(auto it = owning_container.begin(); it != owning_container.end();)
{
std::shared_ptr<int> const& i = *it;
if(*i % 10 == 0)
{
it = owning_container.erase(it);
}
else
{
++it;
}
}

// Now go through the referencing container and print out all values.
// If we were dealing with raw pointers in both containers here we would access deleted memory,
// since some of the the actual resources (in owning_container) that referencing_container
// references have been removed.
for(std::weak_ptr<int> const& i_ref : referencing_container)
{
// Check if the shared resource still exists before using it (purpose of weak_ptr)
std::shared_ptr<int> i = i_ref.lock();
if(i)
{
std::cout << *i << std::endl;
}
}

return 0;
}

这里我们有一个容器,其中包含一些共享资源 - 在本例中为整数 - ( shared_ptr ),另一个容器需要引用 ( weak_ptr )。引用不拥有资源,它只需要能够访问它如果它存在。为了判断被引用的资源是否仍然存在,我们将 weak_ptr 转换为到 shared_ptr使用 weak_ptr::lock() .那些仍然存在的资源将具有有效的 shared_ptrlock() 返回.那些不再存在的将返回 null shared_ptr . shared_ptr有一个 operator bool()我们可以在尝试使用它之前检查它是否为 null。

如果您制作的游戏中的每个对象都由 game_object 表示,那么情况可能不太复杂。 .假设您有某种寻找敌人的逻辑,需要目标 game_object寻求。使用上面的方法,你可以让敌人捕获 weak_ptr<game_object> .它不拥有这个 game_object .如果其他东西杀死了它的目标,它的目标就应该死;如果敌人持有 shared_ptr 会发生这种情况,不会卡在某种边缘状态反而。这样如果敌人的目标还活着(它可以通过锁定 weak_ptr 来检查),它可以执行搜索逻辑;否则它可以找到新的目标。 game_object 的“所有者”可能是某种 game_world类 - 这将有一个容器 shared_ptr<game_object> .当敌人需要一个新目标时,它可以搜索这个容器并创建它的 weak_ptr来自 game_worldshared_ptr .

关于c++ - shared_ptr中weak_ptr的作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25223639/

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