#include <iostream>
#include <string>
#include <memory>
class TestB;
class TestA{
public:
void run()
{
std::cout << "TestA" << std::endl;
}
void setPt(std::shared_ptr<TestB>& p)
{
ptb = p;
std::cout << ptb.use_count() << std::endl;
}
std::weak_ptr<TestB> ptb;
};
class TestB{
public:
void run()
{
std::cout << "TestB" << std::endl;
std::shared_ptr<TestA> tmp = pta.lock();
tmp->run();
std::cout << tmp.use_count() << std::endl;
}
void setPt(std::shared_ptr<TestA>& p)
{
pta = p;
std::cout << pta.use_count() << std::endl;
}
std::weak_ptr<TestA> pta;
};
class TestC{
public:
void run()
{
std::cout << "TestC" << std::endl;
}
void setPt(std::shared_ptr<TestA>& p)
{
pta = p;
std::cout << pta.use_count() << std::endl;
}
std::shared_ptr<TestA> pta;
};
auto myAdelete = [](TestA* pt){
std::cout << "delete pta" << std::endl;
delete pt;
pt = nullptr;
};
auto myBdelete = [](TestB* pt){
std::cout << "delete ptb" << std::endl;
delete pt;
pt = nullptr;
};
auto myCdelete = [](TestC* pt){
std::cout << "delete ptc" << std::endl;
delete pt;
pt = nullptr;
};
auto myDelete = [](){};
int main()
{
std::shared_ptr<TestA> pta(new TestA, myAdelete);
std::shared_ptr<TestB> ptb(new TestB, myBdelete);
std::shared_ptr<TestC> ptc(new TestC, myCdelete);
ptb->setPt(pta);
ptc->setPt(pta);
pta->setPt(ptb);
ptb->run();
return 0;
}