std::shared_ptr Circular Reference Causing Resource Not Freed in C++17
Does anyone know how to Hey everyone, I'm running into an issue that's driving me crazy. I am working with a question with `std::shared_ptr` in my C++17 application. I have two classes, `A` and `B`, that reference each other, leading to a circular reference. Despite my expectation that the smart pointers would manage memory correctly, I am left with memory leaks when I try to release resources. Hereโs a simplified version of my code: ```cpp #include <iostream> #include <memory> class B; // Forward declaration class A { public: std::shared_ptr<B> b; ~A() { std::cout << "A destroyed" << std::endl; } }; class B { public: std::shared_ptr<A> a; ~B() { std::cout << "B destroyed" << std::endl; } }; int main() { std::shared_ptr<A> a = std::make_shared<A>(); std::shared_ptr<B> b = std::make_shared<B>(); a->b = b; b->a = a; return 0; } ``` When I run this code, I see that neither destructor for `A` nor `B` is invoked, which indicates that they are not being freed. I have tried replacing one of the `std::shared_ptr` references with `std::weak_ptr`, thinking it might resolve the circular dependency: ```cpp class B { public: std::weak_ptr<A> a; ~B() { std::cout << "B destroyed" << std::endl; } }; ``` However, when I do this, I get a runtime behavior when I try to access `a` in class `B`. When I check the `weak_ptr`, it seems to be expired. I am unsure how to properly use `weak_ptr` here or if thereโs a better design pattern to avoid the circular reference without compromising resource management. Any advice on how to address this scenario would be greatly appreciated! For context: I'm using Cpp on Windows. Thanks in advance! I'm on CentOS using the latest version of Cpp. The project is a CLI tool built with Cpp. Am I approaching this the right way? I recently upgraded to Cpp 3.10. Cheers for any assistance!