c++ - shared_ptr 不会在程序结束时破坏对象

标签 c++ c++11 queue smart-pointers

我正在尝试使用智能指针实现双端队列。但是,我注意到在程序结束时,双端队列的节点没有被正确破坏。
这是代码:

#include<iostream>
#include<memory>


class Node
{
  int value;
  std::shared_ptr<Node> next = nullptr;
  std::shared_ptr<Node> prev = nullptr;

public:
  Node() = default;
  Node(int val): value(val) {}
  ~Node()
  {
    std::cout << "Destructor of node: " << value << std::endl;
  }
  friend class Deque;
};

class Deque
{
  using pointer = std::shared_ptr<Node>; 
  pointer head = nullptr;      // pointer to the first element of the queue
  pointer tail = nullptr;      // pointer to the last element of the queue 

public:
  Deque() = default;
  ~Deque(){ std::cout << "Dequeue destructor" << std::endl; }
  
  bool is_empty()
  {
    if (head == nullptr && tail == nullptr )
      return true;
    else
      return false;
  }
  void push_back(const pointer& val)
  {
    if (is_empty())
      {
        head = val;
        tail = val;
      }
    else
      {
        val->prev = tail;
        tail->next = val;
        tail = val;
      }
  }
};



int main()
{
  Deque DEQ;  
  auto node1 = std::make_shared< Node >(1);
  auto node2 = std::make_shared< Node >(2);
  auto node3 = std::make_shared< Node >(3);

  DEQ.push_back(node1);
  DEQ.push_back(node2);

  std::cout << "Use count node1 = " << node1.use_count() << std::endl;
  std::cout << "Use count node2 = " << node2.use_count() << std::endl;
  std::cout << "Use count node3 = " << node3.use_count() << std::endl;
 
  return 0;
}
输出如下:
Use count node1 = 3
Use count node2 = 3
Use count node3 = 1
Destructor of node: 3
Dequeue destructor
当我推 node1node2进入双端队列,它们在程序结束时不会被破坏,而 node3被正确破坏。
我认为问题在于 node1 的引用计数和 node2等于 3。你知道我可以如何改变我的实现来解决这个问题吗?谢谢。

最佳答案

I assume the problem is that the reference count of node1 and node2 is equal to 3.


你的假设是正确的。共享指针不会破坏指向的对象,直到引用计数降至零。

Do you know how I can change my implementation in order to solve this problem?


所有权图中没有循环。例如,您可以在列表的一个方向使用拥有智能指针,而在另一个方向使用非拥有指针(可能是弱指针)。

关于c++ - shared_ptr 不会在程序结束时破坏对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64282322/

相关文章:

c++ - 如何从 FAILED(HRESULT) 引发 std::system_error 异常?

c++ - 从 Ubuntu 运行一个可执行文件到 Debian

c++ - 模板 vector 的 vector

c++ - 在 for - range 循环中删除项目的最快方法

C++ 可变参数模板 AND 和 OR

java - 创建一个小队列(泛型)

c++ - 这些析构函数调用背后的逻辑是什么

c++ - 知道使用 std::once_flag 而不调用 std::call_once (任务成功完成后设置once_flag)

python - 由于阻塞 Queue.get() 方法导致的死锁

linux - 是否有命令查看某个用户在队列中有多少作业?