How do I avoid cycles with shared_ptr and weak_ptr in C++?

In C++, when using smart pointers like shared_ptr and weak_ptr, it's essential to avoid cycles that can lead to memory leaks. A cycle occurs when two or more objects reference each other through shared_ptr, preventing their memory from being released. To circumvent this problem, you can use weak_ptr for one of the references in the cycle. This way, the weak pointer does not contribute to the reference count, allowing the involved objects to be deleted when they are no longer needed.

Here’s an example that demonstrates how to avoid cycles using shared_ptr and weak_ptr in C++:

#include <iostream> #include <memory> class B; // Forward declaration class A { public: std::shared_ptr bPtr; ~A() { std::cout << "A destroyed" << std::endl; } }; class B { public: std::weak_ptr aPtr; // weak_ptr to avoid cycle ~B() { std::cout << "B destroyed" << std::endl; } }; int main() { std::shared_ptr a = std::make_shared(); std::shared_ptr b = std::make_shared(); a->bPtr = b; b->aPtr = a; // Now B holds a weak_ptr to A return 0; // Both A and B will be destroyed properly }

Avoid cycles shared_ptr weak_ptr memory leaks C++ smart pointers reference counting