zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    久违了,我的博客
    眼前一亮的WI微逸输入法
    致第一次安装(yong)小小输入法的你
    输入法使用体验及引申
    小小输入法使用小记
    RIME-使用小心得
    FreeRTOS run on eclipse
    流行输入法使用小记
    FreeBSD虚拟机——小折腾
    vmware版本选择
  • 原文地址:https://www.cnblogs.com/osbreak/p/9209104.html
Copyright © 2011-2022 走看看