Зміст курсу
C++ Smart Pointers
C++ Smart Pointers
Breaking Circular References With Weak Pointers
As we saw in the previous section, circular references occur when two (or more) shared pointers reference each other in a loop, creating a deadly cycle. This interdependence prevents the destructor of the object from being called, as the reference counts never reach zero. The result is a very common memory leak which became the primary reason why weak pointers were introduced.
Breaking the cycle with weak pointers
Weak pointers are purpose-built to break these cycles. By replacing a shared pointer in a circular reference with a weak pointer, we can ensure that one of the objects does not artificially extend the lifetime of another in a manner that would prevent either from being destroyed.
To understand this concept better, let’s rewrite the linked-list circular reference problem we discussed in the previous section using a weak pointer.
main
#include <iostream> #include <memory> class Node { public: // A weak pointer to the next element prevents circular ownership. std::weak_ptr<Node> next; // The constructor. Node() { std::cout << "Node constructed." << std::endl; } // The destructor. ~Node() { std::cout << "Node destructed." << std::endl; } }; 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, // thus preventing a circular reference. node1->next = node2; node2->next = node3; node3->next = node1; // Now when node1, node2, and node3 go out of scope, their destructors will be called, // and the memory will be properly deallocated. }
In the above code, we fixed our circular reference problem by changing next
from being a shared pointer to a weak pointer. Follow the comments in the above code for better understanding. And don’t forget to run the code to see the destructors being called now. No memory leaks!
Дякуємо за ваш відгук!