Weakポインタによる循環参照の解消
メニューを表示するにはスワイプしてください
weakポインタは循環参照を解消するために設計されています。循環依存関係にあるstd::shared_ptrをstd::weak_ptrに置き換えることで、オブジェクト同士が互いの寿命を意図せず延長することを防ぎ、適切な破棄が可能になります。
main.cpp
12345678910111213141516171819202122232425#include <iostream> #include <memory> class Node { public: Node() { std::cout << "Node constructed." << std::endl; } ~Node() { std::cout << "Node destructed." << std::endl; } // A weak pointer to the next element prevents circular ownership. std::weak_ptr<Node> next; }; int main() { // Creating three Node objects. std::shared_ptr<Node> node1 = std::make_shared<Node>(); std::shared_ptr<Node> node2 = std::make_shared<Node>(); std::shared_ptr<Node> node3 = std::make_shared<Node>(); // Creating a list where the last node's next is a weak pointer node1->next = node2; node2->next = node3; node3->next = node1; // Now when node1, node2, and node3 go out of scope, their destructors will be called }
循環参照の問題は、nextをstd::shared_ptrからstd::weak_ptrに変更することで解決されます。コード内のコメントを参照して理解を深めてください。コードを実行して、デストラクタが正しく呼び出されること(メモリリークなし)を確認しましょう。
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 12
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 1. 章 12