将链表从原始指针转换为智能指针
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++
类实例时,必须使用new
和delete
,而不能使用malloc
和free
。malloc
和free
是C库函数,它们完全不了解c++类的构造函数、析构函数以及其他与c++类相关的所有内容。
显示的代码试图通过使用malloc
来构造node
类的实例。这行不通。必须使用new
来构造它:
std::shared_ptr<node> link = new node;
这比由malloc
和丑陋的cast组成的c风格的混合物更短更整洁。
您提到您正在将C代码转换为c++。转换的强制部分是将所有malloc
和free
调用替换为new
和delete
。
相关文章:
- 正在将指针转换为范围
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- C++:Lambda 函数指针转换的用例是什么?
- 如何将 int 指针转换为浮点指针
- 为什么在将 void 指针转换为整数指针时出现分段错误
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- 我们可以在不知道其真实类型的情况下将基类指针转换为派生类指针吗?
- C++中数组大小未知的指针转换
- Antlr cpp 运行时 任何错误的指针转换?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- C 指针转换会导致内存访问冲突
- 模板类实例化中的指针转换无效
- 函数调用歧义(用户定义的转换和 Derived2Base 指针转换)
- 如何将 void(*)() 类型的指针转换为 void*
- 数组到指针转换期间的临时具体化
- 直接为浮点变量分配十六进制整数与通过指针转换分配之间的区别
- 将基类指针转换为派生的类指针
- 应对 std::字符串中的 std::<char>指针转换后的向量
- 在编译时将函数指针转换为 std::uintptr_t
- 将基类指针转换为未知派生类指针