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;
    }
  • 相关阅读:
    linux下光标定位和清屏函数
    使用NHibernate的时候出现“指定的转换无效”的错误
    UI 界面:技术决定一切
    BeamTarget红外线的末尾
    Chicken的代码解剖:6 PlayerController
    kismet模块创建
    Projectile重构
    关卡设计师优化关卡
    一些主类的继承关系
    EA iOS平台《质量效应》《死亡空间》的界面
  • 原文地址:https://www.cnblogs.com/osbreak/p/9209104.html
Copyright © 2011-2022 走看看