std::weak_ptr

weak_ptr 是一种不控制对象生命周期的智能指针, 它指向一个 shared_ptr 管理的对象. 
进行该对象的内存管理的是那个强引用的 shared_ptr. 
weak_ptr只是提供了对管理对象的一个访问手段. 
为了解决std::shared_ptr在相互引用的情况下出现的问题而存在的,
std::shared_ptr赋值给weak_ptr时,weak_ptr 支持拷贝或赋值,不会引起智能指针计数增加。
weak_ptr.lock() 获取所管理的对象的强引用(shared_ptr)
weak_ptr.use_count() 返回与 shared_ptr 共享的对象的引用计数.
weak_ptr.reset() 将 weak_ptr 置空
#include <cstdio>
#include <iostream>
#include <memory>

using namespace std;

struct Child;
typedef std::weak_ptr<Child> STChildWeakPtr;

struct Father : public std::enable_shared_from_this<Father>
{
    string say;
    STChildWeakPtr ChildWeakPtr;
};
typedef std::weak_ptr<Father> STFatherWeakPtr;

struct Child : public std::enable_shared_from_this<Child>
{
    string say;
    STFatherWeakPtr FathWeakPtr;
};

int main()
{
    //创建zh指针
    std::shared_ptr<Father> fa(new Father);
    fa->say = "Iam father";
    std::shared_ptr<Child> ch(new Child);
    ch->say = "Iam Child";

    //赋值给weak_ptr
    fa->ChildWeakPtr = ch;
    ch->FathWeakPtr = fa;

    //通过weak_ptr获取指针对象
    std::shared_ptr<Father> ff = ch->FathWeakPtr.lock();
    cout << ff->say <<endl;

    std::shared_ptr<Child> cc = fa->ChildWeakPtr.lock();
    cout << cc->say << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/osbreak/p/9209104.html