C++ 科目二 智能指针 [weak_ptr] (解决shared_ptr的循环引用问题)
shared_ptr引入的重复计数问题,导致内存泄漏
using namespace std;
class CFather;
class CSon;class CFather {
public:CFather(){}void Set(shared_ptr<CSon> pson){Pson = pson;}shared_ptr<CSon> Pson;
};class CSon {
public:CSon(){}void Set(shared_ptr<CFather> pfather){Pfather = pfather;}shared_ptr<CFather> Pfather;
};int main()
{CSon *pson = new CSon();CFather *pfather = new CFather();{shared_ptr<CFather> shared_father(pfather);shared_ptr<CSon> shared_son(pson);shared_father->Set(shared_son);shared_son->Set(shared_father);cout << shared_father.use_count() << endl;cout << shared_son.use_count() << endl;}cout << "It's good to see you!" << endl;return 0;
}
将CFather或者CSon的shared_ptr变成weak_ptr即可避免内存泄漏问题