Reputation: 695
I need to convert a C implementation of a doubly linked list that uses raw pointers, to an implementation using smart pointers instead.
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.
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.
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?
Upvotes: 0
Views: 662
Reputation: 118435
When constructing C++
class instances, you must use new
and delete
, instead of malloc
and free
. 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.
The shown code is attempting to construct an instance of the node
class by using malloc
. that won't work. new
must be used to construct it:
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.
You mentioned that you are in the process of converting C code to C++. A mandatory part of that conversion is to replace all malloc
and free
calls with new
and delete
. This is not optional, this is required for proper C++ code.
Upvotes: 4