我需要将使用原始指针的双向链表的 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++
类实例时,必须使用new
和delete
,而不是malloc
和免费
。 malloc
和 free
是 C 库函数,它们对 C++ 类的构造函数、析构函数以及与 C++ 类有关的所有其他内容一无所知。
显示的代码试图通过使用 malloc
构造 node
类的实例。那是行不通的。必须使用 new
来构造它:
std::shared_ptr<node> link = new node;
这比由 malloc
和丑陋的转换组成的 C 风格混合体更短、更整洁。
您提到您正在将 C 代码转换为 C++。该转换的强制性部分是将所有 malloc
和 free
调用替换为 new
和 delete
。这不是可选的,这是正确的 C++ 代码所必需的。
关于c++ - 将链表从原始指针转换为智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40166769/