Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a list with unique_ptr<>?

As I understand it, a unique_ptr signifies exclusive ownership. A singly linked list seems to fit this, with each node owning the next, like (pseduocode alert)

class node{
public:
      unique_ptr<node> next;
      int value;
};

but I don't understand how to perform operations like traversing the list, where I'm used to doing

here=here->next;

How do you implement data structures using unique_ptr's? Are they the right tool for the job?

like image 705
Alexander Duchene Avatar asked Dec 04 '12 18:12

Alexander Duchene


1 Answers

When you go through the nodes, you don't need to own the node pointer, which means that

here=here->next;

Is incorrect if here is a unique_ptr. Owning an object means "being responsible for it's life and death" which means the owner is the one who have the code that will destroy the object. If you use another definition of owning, then it's not what unique_ptr means.

In you're list node code, you assume that each node is responsible for the next node (if you destroy a node, all the next nodes will be destroyed too). It can be valid behaviour, it depends on your needs, just be sure it's what you really wants.

What you want is to read the pointer without owning it. Current good practice to do this is to use a raw pointer indicating a "use but don't own" kind of usage to other developers looking at this code (unique_ptr means "if I die, the pointed object dies too"):

node* here = nullptr; // it will not own the pointed nodes (don't call delete with this pointer)
here = &first_node(); // assuming first_node() returns a reference to the first node
here = here->next.get(); // to get the next node without owning it: use get() - true in all smart pointers interface
like image 150
Klaim Avatar answered Oct 21 '22 14:10

Klaim