Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Breaking Circular References With Weak Pointers | Weak Pointers
C++ Smart Pointers
course content

Зміст курсу

C++ Smart Pointers

C++ Smart Pointers

1. Introduction to Smart Pointers
2. Unique Pointers
3. Shared Pointers
4. Weak Pointers
5. References
6. Advanced topics

book
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.

cpp

main

copy
12345678910111213141516171819202122232425262728293031323334
#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!

The following code has two shared pointers `A` and `B` both sharing a resource. Modify it so that `B` becomes a weak pointer.

The following code has two shared pointers A and B both sharing a resource. Modify it so that B becomes a weak pointer.

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 3
We're sorry to hear that something went wrong. What happened?
some-alt