#include <iostream>
#include <memory>
using namespace std;
class B;
class A {
public:
// A owns B
shared_ptr<B> b;
~A() {
cout << "A destroyed" << endl;
}
};
class B {
public:
// B only needs to refer to A, not own it
weak_ptr<A> a;
~B() {
cout << "B destroyed" << endl;
}
};
int main() {
{
auto objA = make_shared<A>();
auto objB = make_shared<B>();
// Ownership is one-directional
objA->b = objB;
// Non-owning reference back to A
objB->a = objA;
}
// Both objects are destroyed correctly
cout << "End of scope" << endl;
return 0;
}
Explanation & Logic Summary:std::shared_ptr uses reference counting to manage lifetime.
When two objects own each other, their reference counts never reach zero, so destructors are never called.
The fix is to identify which relationship is non-owning and replace that ownership with std::weak_ptr.
This breaks the cycle while still allowing safe access.
Firmware Relevance & Real-World Context:
In real systems, components often reference each other (managers, callbacks, observers).
Not all references imply ownership. Using weak_ptr for non-owning relationships prevents memory leaks in long-running embedded Linux and RTOS-based applications.
Input
Expected Output
A destroyed B destroyed End of scope