I need some suggestions on my reimplementation of a doubly linked list with smart pointers since I'm new to smart pointers in C++.
I read some docs on smart pointers and found out there are shared_ptr<Obj>
, unique_ptr<Obj>
and weak_ptr<Obj>
. I only use shared_ptr<Obj>
in my current code, but I'm not sure how to use unique_ptr<Obj>
in my doubly linked list. I would like someone can give me some pointers on how and where to use unique_ptr<Obj>
in my DLL.
class Node{
public:
int data;
Node(int data){
this->data = data;
}
public:
shared_ptr<Node> prev;
shared_ptr<Node> next;
};
class LinkedList{
public:
shared_ptr<Node> head;
shared_ptr<Node> tail;
public:
LinkedList(){}
void fun(){
printf("fun()\n");
}
void append(shared_ptr<Node> node){
if(!head){
head = node;
tail = head;
}else{
tail->next = node;
node->prev = tail;
tail = node;
}
}
void print(){
shared_ptr<Node> curr = head;
while(curr){
printf("[%d]\n", curr->data);
curr = curr->next;
}
}
void remove(shared_ptr<Node> node){
shared_ptr<Node> curr = head;
if(node && curr){
while(curr){
if(curr == node){
if(curr->prev == nullptr){
if(curr->next == nullptr){
// [curr]
node.reset();
head.reset();
tail.reset();
}else{
// [curr]->[]
shared_ptr<Node> next = curr->next;
curr->next.reset();
next->prev.reset();
head = next;
}
}else{
if(curr->next == nullptr){
// []->[curr]
shared_ptr<Node> prev = curr->prev;
curr->prev.reset();
prev->next.reset();
tail = prev;
}else{
// []->[curr]->[]
shared_ptr<Node> next = curr->next;
shared_ptr<Node> prev = curr->prev;
next->prev = prev;
prev->next = next;
}
}
}
curr = curr->next;
}
}
}
};