#include <iostream>
#include <memory>
using namespace std;
class Parent;
class Child
{
public:
Child(){
std::cout << "Child construction" << std::endl;
}
~Child(){
std::cout << "Child destruction" << std::endl;
}
weak_ptr<Parent> parent;
};
class Parent
{
public:
Parent(){
std::cout << "Parent construction" << std::endl;
}
~Parent(){
std::cout << "Parent destruction" << std::endl;
}
shared_ptr<Child> child;
int Get() { return 3; };
};
void Test(shared_ptr<Child>& c)
{
std::cout << "3child use count = " << c.use_count() <<std::endl;
shared_ptr<Parent> p(new Parent());
c->parent = p;
p->child = c;
std::cout << "4child use count = " << c.use_count() <<std::endl;
if (shared_ptr<Parent> pp = c->parent.lock())//未过期
{
cout << pp->Get() << endl;
}
else
cout << "expired" << endl;
std::cout << "5child use count = " << c.use_count() <<std::endl;
}
int main()
{
shared_ptr<Child> c(new Child);
std::cout << "1child use count = " << c.use_count() <<std::endl;
Test(c);
std::cout << "2child use count = " << c.use_count() <<std::endl;
if (shared_ptr<Parent> pp = c->parent.lock())//未过期
{
cout << pp->Get() << endl;
}
else{
cout << "expired" << endl;
std::cout << "6child use count = " << c.use_count() <<std::endl;
}
return 0;
}
执行结果:
➜ build ./main
Child construction
1child use count = 1
3child use count = 1
Parent construction
4child use count = 2
3
5child use count = 2
Parent destruction
2child use count = 1
expired
6child use count = 1
Child destruction
➜ build