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;
    }
  • 相关阅读:
    解决win8无法成功安装Windows Phone 7 sdk的问题
    决定专心写博,学习
    时间管理的首要原则:专注力
    Windows Phone 7 开发环境的搭建
    Windows Phone 8 开发环境的搭建
    学习使用ErrorProvider 转载
    SetTimer函数
    网络工程课程笔记
    IP地址分类及特殊IP地址
    windows消息处理机制
  • 原文地址:https://www.cnblogs.com/osbreak/p/9209104.html
Copyright © 2011-2022 走看看