#include <iostream>
#include <memory>
#include <string>
struct B {
std::string s;
};
struct A {
B b;
A(std::string s) : b{s} {};
~A() { std::cout << "A deleted." << std::endl; }
};
void f(std::shared_ptr<B> b) {
std::cout << "in f, b->s = " << b->s << " (use_count=" << b.use_count() << ")"
<< std::endl;
}
int main() {
std::shared_ptr<A> a = std::make_shared<A>("hello");
std::shared_ptr<B> b { a, &(a->b) };
a.reset(); // a now invalid.
std::cout << "before f, b->s = " << b->s << " (use_count=" << b.use_count()
<< ")" << std::endl;
f(std::move(b)); // f now responsible for deleting the A.
std::cout << "after f" << std::endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8bWVtb3J5PgojaW5jbHVkZSA8c3RyaW5nPgoKc3RydWN0IEIgewogIHN0ZDo6c3RyaW5nIHM7Cn07CnN0cnVjdCBBIHsKICBCIGI7CiAgQShzdGQ6OnN0cmluZyBzKSA6IGJ7c30ge307CiAgfkEoKSB7IHN0ZDo6Y291dCA8PCAiQSBkZWxldGVkLiIgPDwgc3RkOjplbmRsOyB9Cn07Cgp2b2lkIGYoc3RkOjpzaGFyZWRfcHRyPEI+IGIpIHsKICBzdGQ6OmNvdXQgPDwgImluIGYsIGItPnMgPSAiIDw8IGItPnMgPDwgIiAodXNlX2NvdW50PSIgPDwgYi51c2VfY291bnQoKSA8PCAiKSIKICAgIDw8IHN0ZDo6ZW5kbDsKfQoKaW50IG1haW4oKSB7CiAgc3RkOjpzaGFyZWRfcHRyPEE+IGEgPSBzdGQ6Om1ha2Vfc2hhcmVkPEE+KCJoZWxsbyIpOwogIHN0ZDo6c2hhcmVkX3B0cjxCPiBiIHsgYSwgJihhLT5iKSB9OwogIGEucmVzZXQoKTsgIC8vIGEgbm93IGludmFsaWQuCiAgc3RkOjpjb3V0IDw8ICJiZWZvcmUgZiwgYi0+cyA9ICIgPDwgYi0+cyA8PCAiICh1c2VfY291bnQ9IiA8PCBiLnVzZV9jb3VudCgpCiAgICA8PCAiKSIgPDwgc3RkOjplbmRsOwogIGYoc3RkOjptb3ZlKGIpKTsgIC8vIGYgbm93IHJlc3BvbnNpYmxlIGZvciBkZWxldGluZyB0aGUgQS4KICBzdGQ6OmNvdXQgPDwgImFmdGVyIGYiIDw8IHN0ZDo6ZW5kbDsKICByZXR1cm4gMDsKfQ==