weak_ptr组织shared_ptr循环引用

#include

#include

#include

class TestB;

class TestA{

public:

void run()

{

std::cout << "TestA" << std::endl;

}

void setPt(std::shared_ptr& p)

{

ptb = p;

std::cout << ptb.use_count() << std::endl;

}

std::weak_ptr ptb;

};

class TestB{

public:

void run()

{

std::cout << "TestB" << std::endl;

std::shared_ptr tmp = pta.lock();

tmp->run();

std::cout << tmp.use_count() << std::endl;

}

void setPt(std::shared_ptr& p)

{

pta = p;

std::cout << pta.use_count() << std::endl;

}

std::weak_ptr pta;

};

class TestC{

public:

void run()

{

std::cout << "TestC" << std::endl;

}

void setPt(std::shared_ptr& p)

{

pta = p;

std::cout << pta.use_count() << std::endl;

}

std::shared_ptr 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 pta(new TestA, myAdelete);

std::shared_ptr ptb(new TestB, myBdelete);

std::shared_ptr ptc(new TestC, myCdelete);

ptb->setPt(pta);

ptc->setPt(pta);

pta->setPt(ptb);

ptb->run();

return 0;

}

你可能感兴趣的:(weak_ptr组织shared_ptr循环引用)