Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#include <iostream> #include <memory> #include <vector> #include <utility> // std::move struct Node { int value; std::unique_ptr<Node> next; explicit Node(int v) : value(v), next(nullptr) { std::cout << "Node(" << value << ") created "; } ~Node() { std::cout << "Node(" << value << ") destroyed "; } }; class LinkedList { public: void prepend(int val) { auto node = std::make_unique<Node>(val); node->next = std::move(head_); // transfer ownership head_ = std::move(node); } void print() const { for (Node* n = head_.get(); n; n = n->next.get()) std::cout << n->value << " -> "; std::cout << "null "; } private: std::unique_ptr<Node> head_; }; // Factory returning unique_ptr std::unique_ptr<std::string> makeGreeting(const std::string& name) { return std::make_unique<std::string>("Hello, " + name + "!"); } int main() { { LinkedList list; list.prepend(3); list.prepend(2); list.prepend(1); list.print(); // all nodes destroyed automatically at end of scope } std::cout << "List destroyed "; auto msg = makeGreeting("unique_ptr"); std::cout << *msg << " "; // unique_ptr cannot be copied — only moved auto p1 = std::make_unique<int>(42); auto p2 = std::move(p1); // p1 is now nullptr std::cout << "p2 = " << *p2 << " "; std::cout << "p1 is " << (p1 ? "not null" : "null") << " "; return 0; }
Result
Open