C++ singly linked list with unique_ptr

A linked list in modern C++ can avoid manual new and delete. Each node owns the next node through a std::unique_ptr, so the whole chain is destroyed automatically when the head goes out of scope. push_front creates a node whose next is the old head, using std::move to transfer ownership.

C++
#include <iostream>
#include <memory>
#include <utility>

struct Node {
  int value;
  std::unique_ptr<Node> next;
  Node(int v, std::unique_ptr<Node> n) : value(v), next(std::move(n)) {}
};

class List {
 public:
  void push_front(int value) { head_ = std::make_unique<Node>(value, std::move(head_)); }

  void reverse() {
    std::unique_ptr<Node> previous;
    while (head_) {
      std::unique_ptr<Node> next = std::move(head_->next);
      head_->next = std::move(previous);
      previous = std::move(head_);
      head_ = std::move(next);
    }
    head_ = std::move(previous);
  }

  void print() const {
    for (const Node* n = head_.get(); n != nullptr; n = n->next.get()) {
      std::cout << n->value << (n->next ? " -> " : "\n");
    }
  }

 private:
  std::unique_ptr<Node> head_;
};

int main() {
  List list;
  for (int v = 4; v >= 1; --v) {
    list.push_front(v);
  }
  list.print();
  list.reverse();
  list.print();
}
Read the full lesson