简体   繁体   English

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

[英]Converting linked list from raw pointers to smart pointers

I need to convert a C implementation of a doubly linked list that uses raw pointers, to an implementation using smart pointers instead. 我需要将使用原始指针的双向链表的C实现转换为使用智能指针的实现。

I have some small experience with smart pointers. 我对智能指针有一些小经验。

Im working on converting the insertFirst() function to get my bearings and understand how this will come together. 我正在转换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;
}

Im having trouble with this line: 我在这行上遇到了麻烦:

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

I thought doing like so: 我以为是这样的:

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

was all I would need. 这就是我所需要的。 But i am less familiar with C and what exactly is happening and why this is not allowed. 但是我对C以及它到底发生了什么以及为什么不允许这样做不那么熟悉。

I get the error: 我得到错误:

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

Can anyone offer some tips and explanation? 谁能提供一些提示和解释?

When constructing C++ class instances, you must use new and delete , instead of malloc and free . 构造C++类实例时,必须使用newdelete ,而不是mallocfree malloc and free are C library functions, that know absolutely nothing about C++ class constructors, destructors, and everything else that goes with what a C++ class is all about. mallocfree是C库函数,它们对C ++类的构造函数,析构函数以及C ++类的所有其他内容一无所知。

The shown code is attempting to construct an instance of the node class by using malloc . 所示代码正在尝试使用malloc构造node类的实例。 that won't work. 那行不通。 new must be used to construct it: 必须使用new来构造它:

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

That's even shorter and neater, than the C-style concoction comprised of malloc , and an ugly cast. 这比由malloc和一个丑陋的演员组成的C风格调料更短,更整洁。

You mentioned that you are in the process of converting C code to C++. 您提到您正在将C代码转换为C ++。 A mandatory part of that conversion is to replace all malloc and free calls with new and delete . 该转换的强制性部分是用newdelete替换所有mallocfree调用。 This is not optional, this is required for proper C++ code. 这不是可选的,这是正确的C ++代码所必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM