oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/cpp/smart_pointers.txt
1.6 KiB, 1 run
created by r1870400018:11952, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | #include <memory> |
| 2 | #include <string> |
| 3 | #include <vector> |
| 4 | #include <iostream> |
| 5 | |
| 6 | class Node { |
| 7 | public: |
| 8 | explicit Node(std::string name) |
| 9 | : name_(std::move(name)) {} |
| 10 | |
| 11 | void add_child(std::unique_ptr<Node> child) { |
| 12 | child->parent_ = this; |
| 13 | children_.push_back(std::move(child)); |
| 14 | } |
| 15 | |
| 16 | const std::string& name() const noexcept { return name_; } |
| 17 | |
| 18 | void print(int depth = 0) const { |
| 19 | for (int i = 0; i < depth; ++i) std::cout << " "; |
| 20 | std::cout << name_ << "\n"; |
| 21 | for (const auto& child : children_) { |
| 22 | child->print(depth + 1); |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | private: |
| 27 | std::string name_; |
| 28 | Node* parent_ = nullptr; |
| 29 | std::vector<std::unique_ptr<Node>> children_; |
| 30 | }; |
| 31 | |
| 32 | class Registry { |
| 33 | public: |
| 34 | std::shared_ptr<Node> get_or_create(const std::string& name) { |
| 35 | for (const auto& node : nodes_) { |
| 36 | if (node->name() == name) { |
| 37 | return node; |
| 38 | } |
| 39 | } |
| 40 | auto node = std::make_shared<Node>(name); |
| 41 | nodes_.push_back(node); |
| 42 | return node; |
| 43 | } |
| 44 | |
| 45 | size_t size() const noexcept { return nodes_.size(); } |
| 46 | |
| 47 | private: |
| 48 | std::vector<std::shared_ptr<Node>> nodes_; |
| 49 | }; |
| 50 | |
| 51 | int main() { |
| 52 | auto root = std::make_unique<Node>("root"); |
| 53 | root->add_child(std::make_unique<Node>("child1")); |
| 54 | root->add_child(std::make_unique<Node>("child2")); |
| 55 | root->print(); |
| 56 | |
| 57 | Registry reg; |
| 58 | auto a = reg.get_or_create("alpha"); |
| 59 | auto b = reg.get_or_create("beta"); |
| 60 | auto a2 = reg.get_or_create("alpha"); |
| 61 | std::cout << "registry size: " << reg.size() << "\n"; |
| 62 | std::cout << "same? " << (a.get() == a2.get() ? "yes" : "no") << "\n"; |
| 63 | |
| 64 | return 0; |
| 65 | } |