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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With