shared_ptr unique_ptr list 自动析构

参考博客:https://www.zhihu.com/question/40265434

这东西的析构不是递归的,就是从头到尾。用来实现链表很合适,但是写指针的时候要小心,特别是unique_ptr

#include <iostream>
#include <string>
#include <memory>

using namespace std;

class UniquePtrNode{
public: 
    UniquePtrNode(int _data):data(_data),next(nullptr){}
    ~UniquePtrNode(){
        cout << data << " des.\n";
    }

  int data;
    unique_ptr<UniquePtrNode> next;
};

class SharedPtrNode{
public:
    SharedPtrNode(int _data):data(_data),next(nullptr){}
    ~SharedPtrNode(){
        cout << data << " des.\n";
    }

  int data;
    shared_ptr<SharedPtrNode> next;
};

void test_share_ptr_list(int n)
{
  shared_ptr<SharedPtrNode> head = nullptr;
  shared_ptr<SharedPtrNode> tail = nullptr;

  for (int i = 0;i < n;++i) {
    if (tail == nullptr) {
      head = make_shared<SharedPtrNode>(i);
      tail = head;
    }
    else {
      tail->next = make_shared<SharedPtrNode>(i);
      tail = tail->next;
    }
  }

  tail = head;
  while(tail!=nullptr)
  {
    cout<<tail->data<<endl;
    tail = tail->next;
  }
}

void test_unique_ptr_list(int n) {
  unique_ptr<UniquePtrNode> head = nullptr;
  unique_ptr<UniquePtrNode> *tail = nullptr;

  for (int i = 0; i < n; i++) {
    if (head == nullptr) {
      head = make_unique<UniquePtrNode>(i);
      tail = &(head);
    }
    else {
      (*tail)->next = make_unique<UniquePtrNode>(i);
      tail = &((*tail)->next);
    }
  }

  tail = &head;
  while((*tail)!=nullptr)
  {
    cout<<(*tail)->data<<endl;
    tail = &((*tail)->next);
  }
}


int main()
{
  int n=10;
  // test_share_ptr_list(n);
  test_unique_ptr_list(n);
  return 0;
}

结果:

0
1
2
3
4
5
6
7
8
9
0 des.
1 des.
2 des.
3 des.
4 des.
5 des.
6 des.
7 des.
8 des.
9 des.
文章目录