将链表从原始指针转换为智能指针

Converting linked list from raw pointers to smart pointers

本文关键字:指针 转换 智能 原始 链表      更新时间:2023-10-16

我需要将使用原始指针的双链表的C实现转换为使用智能指针的实现。

我有一些使用智能指针的小经验。

我正在转换insertFirst()函数以获得我的轴承并理解这将如何结合在一起。

struct node {
  int data;
  int key;
  std::shared_ptr<node> next;
  std::weak_ptr<node> prev;
};
void insertFirst(int key, int data){
  //create a link
  //struct node *link = (struct node*) malloc(sizeof(struct node));
  std::shared_ptr<node> link = (std::shared_ptr<node>) malloc(sizeof(struct node));
  link->key = key;
  link->data = data;
  if(isEmpty()){
    //make it the last link
    last = link;
  }else {
    //update first prev link
    head->prev = link;
  }
  //point it to old first link
  link->next = head;
  //point first to new first link
  head = link;
}

这一行我有问题:

struct node *link = (struct node*) malloc(sizeof(struct node));

我想这样做:

std::shared_ptr<node> link = (std::shared_ptr<node>) malloc(sizeof(struct node));

是我所需要的。但我不太熟悉C和到底发生了什么,为什么这是不允许的。

我得到错误:

no matching conversion for C-style cast from 'void *' to 'std::shared_ptr<node>'

谁能提供一些提示和解释?

在构建C++类实例时,必须使用newdelete,而不能使用mallocfreemallocfree是C库函数,它们完全不了解c++类的构造函数、析构函数以及其他与c++类相关的所有内容。

显示的代码试图通过使用malloc来构造node类的实例。这行不通。必须使用new来构造它:

std::shared_ptr<node> link = new node;

这比由malloc和丑陋的cast组成的c风格的混合物更短更整洁。

您提到您正在将C代码转换为c++。转换的强制部分是将所有mallocfree调用替换为newdelete