I am trying to use smart pointers (std::unique_ptr
) to create a singly linked list. Here is an example of a singly linked list with raw pointer.
struct Node {
int data;
Node *next = nullptr;
Node(int data) : data{data}, next{nullptr} {}
~Node() { std::cout << "Destroy node with data: " << data << '\n'; }
};
void print_list(Node *head) {
while (head != nullptr) {
cout << head->data << " --> ";
head = head->next;
}
cout << "nullptr" << std::endl;
}
void insert(Node *&head, int data) {
Node *new_node = new Node{data};
new_node->next = head;
head = new_node;
}
int main(int argc, char *argv[]) {
Node *head = nullptr;
for (int i = 0; i < 5; ++i) {
insert(head, i);
}
print_list(head);
return 0;
}
The output is:
4 --> 3 --> 2 --> 1 --> 0 --> nullptr
Apparently there is memory leak in the above code (destructor is not called). Now I want to use smart pointer to achieve the same thing:
struct Node {
int data = 0;
std::unique_ptr<Node> next;
Node(int data) : data{data}, next{nullptr} {}
~Node() { std::cout << "Destroy node with data: " << data << '\n'; }
};
void print_list(std::unique_ptr<Node> head) {
while (head != nullptr) {
std::cout << head->data << " --> ";
head = std::move(head->next);
}
std::cout << "nullptr" << std::endl;
}
void insert(std::unique_ptr<Node> &&head, int data) {
std::unique_ptr<Node> new_node{std::make_unique<Node>(data)};
new_node->next = std::move(head);
head = std::move(new_node);
}
// g++ -std=c++17 -Wall 2_1.cpp && ./a.out
int main(int argc, char *argv[]) {
std::unique_ptr<Node> head{nullptr};
for (int i = 0; i < 5; ++i) {
insert(std::move(head), i);
}
print_list(std::move(head));
return 0;
}
The output is:
4 --> Destroy node with data: 4
3 --> Destroy node with data: 3
2 --> Destroy node with data: 2
1 --> Destroy node with data: 1
0 --> Destroy node with data: 0
nullptr
We can observe that the life time of new_node
ends when insert()
returns. I would like to know if it's possible to use smart pointers to achieve singly linked list and retains the functions interface as above.