链接:C++:智能指针(2)——shared_ptr引用计数功能,weak_ptr解决循环引用_cocoa0409的博客-CSDN
这一篇代码比较完整
C++智能指针weak_ptr详解_sinat_31608641的博客-CSDN博客_weakptr
如果不用weak_ptr,结果如下:导致无法析构
using namespace std;
class Parent;
class Child
{
public:
shared_ptr<Parent> parent;
Child() { cout << "hello Child" << endl; };
~Child() { cout << "bye Child" << endl; };
};
class Parent
{
public:
shared_ptr<Child> child;
Parent() { cout << "hello Parent" << endl; };
~Parent() { cout << "bye Parent" << endl; };
int GetNum(){return num;}
void AddNum(){num++;}
private:
int num = 0;
};
void ShowInfo()
{
shared_ptr<Parent> parent(new Parent());
shared_ptr<Child> child(new Child());
parent->child = child;
child->parent = parent;
for (int i = 0; i < 10; ++i){parent->AddNum();}
if (shared_ptr<Parent> var = child->parent)//如果未过期
{
cout << "Parent num is:" << var->GetNum() << endl;
}
else
cout << "Parent is expired" << var->GetNum() << endl;
}
int main()
{
ShowInfo();
return 0;
}
采用weak_ptr,结果如下:解决循环引用问题
using namespace std;
class Parent;
class Child
{
public:
Child()=default;
~Child() = default;
weak_ptr<Parent> parent;
};
class Parent
{
public:
Parent() = default;
~Parent() = default;
shared_ptr<Child> child;
int Get() { return 3; };
};
void Test(shared_ptr<Child>& c)
{
shared_ptr<Parent> p(new Parent());
c->parent = p;
p->child = c;
if (shared_ptr<Parent> pp = c->parent.lock())//未过期
{
cout << pp->Get() << endl;
}
else
cout << "expired" << endl;
}
int main()
{
shared_ptr<Child> c(new Child);
Test(c);
if (shared_ptr<Parent> pp = c->parent.lock())//未过期
{
cout << pp->Get() << endl;
}
else
cout << "expired" << endl;
return 0;
}