C++ 弱ptr在共享ptr中的作用

C++ 弱ptr在共享ptr中的作用,c++,shared-ptr,smart-pointers,weak-ptr,cyclic-reference,C++,Shared Ptr,Smart Pointers,Weak Ptr,Cyclic Reference,我了解共享的ptr是如何工作的,除了弱者的角色。我知道当引用计数不为零时,它可以检测循环引用,但除此之外,我不知道它是如何做到这一点的。它的作用是什么?另请参见:了解原因和方式 我将提供一个示例,说明我是如何使用它的,尽管我编写的示例代码有点复杂,请耐心听我说: #include <vector> #include <memory> #include <ostream> int main() { // Fill container with values

我了解共享的ptr是如何工作的,除了弱者的角色。我知道当引用计数不为零时,它可以检测循环引用,但除此之外,我不知道它是如何做到这一点的。它的作用是什么?

另请参见:了解原因和方式

我将提供一个示例,说明我是如何使用它的,尽管我编写的示例代码有点复杂,请耐心听我说:

#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;
}
#包括
#包括
#包括
int main()
{
//用值1-50填充容器。此容器拥有这些值。
std::向量容器;

对于(int i=1;i弱指针不声明资源的所有权,只引用它。因此,它们不允许您以任何方式对资源进行操作,除非再次声明所有权(使用
弱ptr::lock()
方法).IMHO,在现实生活中,这种行为最常见的情况是循环依赖和(不太常见的)缓存

仅使用共享指针生成的循环依赖关系实际上是内存泄漏,因为指针的相互引用计数永远不会小于1:如果没有其他东西拥有A,则B仍然拥有A,反之亦然。弱指针不会“检测”这种情况。只要打破所有权循环,它就不会让问题发生。您可能会仍然通过锁定弱指针来“连接链的末端”,但是您可能通过弱指针获得的共享指针都不会持久


缓存的问题是,缓存通常不会影响缓存内容的生存期,这不是缓存的职责。但是,如果缓存包含共享指针,则您将无法在不与缓存对话的情况下终止缓存对象的生存期,这通常会带来不便。

可能重复当然不是,弱指针在解析循环引用时很少有用。它们在其他方面更有用。@PeterClark我无法从Q中理解答案,关于弱ptr的部分不是很连贯。通常共享ptr很好,在使用弱ptr传递参数时,将一些共享信息存储在标准容器中的某个地方er在函数调用中。@user997112抱歉,没有看到您对我的答复。我认为一般做法是,如果您对答案进行了评论,就对答案进行评论(不确定如果您对问题本身进行了评论,而我没有对该问题进行评论,它是否会通知我).有什么特别让人困惑的吗?有一件事需要澄清-你是在寻找弱ptr的工作原理,还是为什么要使用它?我回答第二个问题(这就是你的标题所暗示的),但你的问题的主体听起来像是在寻找第一个。你能提供弱引用有帮助的循环依赖性案例的例子吗?