簡體   English   中英

將鏈接列表從原始指針轉換為智能指針

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

我需要將使用原始指針的雙向鏈表的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 ,而不是mallocfree mallocfree是C庫函數,它們對C ++類的構造函數,析構函數以及C ++類的所有其他內容一無所知。

所示代碼正在嘗試使用malloc構造node類的實例。 那行不通。 必須使用new來構造它:

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

這比由malloc和一個丑陋的演員組成的C風格調料更短,更整潔。

您提到您正在將C代碼轉換為C ++。 該轉換的強制性部分是用newdelete替換所有mallocfree調用。 這不是可選的,這是正確的C ++代碼所必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM