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