Hard
Parent and child injected with shared_ptrs to each other
Parent and Child are wired together via constructor-injected shared_ptrs, each holding a shared_ptr back to the other so either can reach the other at any time. What happens after main returns?
main.cpp
struct Child;
struct Parent {
std::shared_ptr<Child> child;
~Parent() { std::cout << "~Parent\n"; }
};
struct Child {
std::shared_ptr<Parent> parent; // injected back-reference, also shared_ptr
~Child() { std::cout << "~Child\n"; }
};
int main() {
auto p = std::make_shared<Parent>();
auto c = std::make_shared<Child>();
p->child = c;
c->parent = p;
// p and c go out of scope here
}20 of 44 in Design Patterns