C++ linked lists with unique ownership
std::unique_ptr expresses exclusive ownership of a dynamically allocated object. Moving it transfers ownership and leaves the source empty.
C++
#include <iostream>
#include <memory>
#include <utility>
struct Node {
int value;
std::unique_ptr<Node> next;
explicit Node(int v) : value(v) {}
};
int main() {
auto head = std::make_unique<Node>(2);
head->next = std::make_unique<Node>(3);
auto first = std::make_unique<Node>(1);
first->next = std::move(head);
head = std::move(first);
for (const Node* current = head.get(); current; current = current->next.get()) {
std::cout << current->value << '\n';
}
}