#include <iostream>
#include <memory>  // For shared_ptr and weak_ptr

class B;  // Forward declaration of class B

class A {
public:
    std::shared_ptr<B> ptrB;  // A holds a shared_ptr to B
    ~A() { std::cout << "A destroyed\n"; }
};

class B {
public:
    std::weak_ptr<A> ptrA;  // B holds a weak_ptr to A to avoid circular reference
    ~B() { std::cout << "B destroyed\n"; }
};

int main() {
    // Create two shared_ptr objects for A and B
    std::shared_ptr<A> a = std::make_shared<A>();
    std::shared_ptr<B> b = std::make_shared<B>();

    // Set up the references
    a->ptrB = b;  // A holds a shared_ptr to B
    b->ptrA = a;  // B holds a weak_ptr to A (to avoid circular dependency)

    // When main ends, both A and B are destroyed correctly
    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: