#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;
}