shared_ptr是带引用计数的智能指针,可以说大部分的情形选择用shared_ptr不会出问题。那么weak_ptr是什么,应该怎么用呢?
weak_ptr也是智能指针,但是比较弱,感觉没什么用。其实它的出现是伴随shared_ptr而来,尤其是解决了一个引用计数导致的问题:在存在循环引用的时候会出现内存泄漏。
关于循环引用,看下面这个小例子就足够了:

#include <iostream>
#include <boost/smart_ptr.hpp>
using namespace std;
using namespace boost;

class BB;
class AA
{
public:
AA() { cout << "AA::AA() called" << endl; }
~AA() { cout << "AA::~AA() called" << endl; }
shared_ptr<BB> m_bb_ptr; //!
};

class BB
{
public:
BB() { cout << "BB::BB() called" << endl; }
~BB() { cout << "BB::~BB() called" << endl; }
shared_ptr<AA> m_aa_ptr; //!
};

int main()
{
shared_ptr<AA> ptr_a (new AA);
shared_ptr<BB> ptr_b ( new BB);
cout << "ptr_a use_count: " << ptr_a.use_count() << endl;
cout << "ptr_b use_count: " << ptr_b.use_count() << endl;
//下面两句导致了AA与BB的循环引用,结果就是AA和BB对象都不会析构
ptr_a->m_bb_ptr = ptr_b;
ptr_b->m_aa_ptr = ptr_a;
cout << "ptr_a use_count: " << ptr_a.use_count() << endl;
cout << "ptr_b use_count: " << ptr_b.use_count() << endl;
}

可以看到由于AA和BB内部的shared_ptr各自保存了对方的一次引用,所以导致了ptr_a和ptr_b销毁的时候都认为内部保存的指针计数没有变成0,所以AA和BB的析构函数不会被调用。解决方法就是把一个shared_ptr替换成weak_ptr。

#include <iostream>
#include <boost/smart_ptr.hpp>
using namespace std;
using namespace boost;

class BB;
class AA
{
public:
AA() { cout << "AA::AA() called" << endl; }
~AA() { cout << "AA::~AA() called" << endl; }
weak_ptr<BB> m_bb_ptr; //!
};

class BB
{
public:
BB() { cout << "BB::BB() called" << endl; }
~BB() { cout << "BB::~BB() called" << endl; }
shared_ptr<AA> m_aa_ptr; //!
};

int main()
{
shared_ptr<AA> ptr_a (new AA);
shared_ptr<BB> ptr_b ( new BB);
cout << "ptr_a use_count: " << ptr_a.use_count() << endl;
cout << "ptr_b use_count: " << ptr_b.use_count() << endl;
//下面两句导致了AA与BB的循环引用,结果就是AA和BB对象都不会析构
ptr_a->m_bb_ptr = ptr_b;
ptr_b->m_aa_ptr = ptr_a;
cout << "ptr_a use_count: " << ptr_a.use_count() << endl;
cout << "ptr_b use_count: " << ptr_b.use_count() << endl;
}

关于shared_ptr与weak_ptr的使用

C++智能指针 weak_ptr

weak_ptr 是一种不控制对象生命周期的智能指针, 它指向一个 shared_ptr 管理的对象. 进行该对象的内存管理的是那个强引用的 shared_ptr. weak_ptr只是提供了对管理对象的一个访问手段. 
  weak_ptr 设计的目的是为配合 shared_ptr 而引入的一种智能指针来协助 shared_ptr 工作, 它只可以从一个 shared_ptr 或另一个 weak_ptr 对象构造, 它的构造和析构不会引起引用记数的增加或减少. 
  定义在 memory 文件中(非memory.h), 命名空间为 std.

  weak_ptr 使用:

std::shared_ptr<int> sp(new int(10));
std::weak_ptr<int> wp(sp);
wp = sp;
printf("%d\n", wp.use_count()); // 1
wp.reset();
printf("%d\n", wp); // 0

// 检查 weak_ptr 内部对象的合法性.
if (std::shared_ptr<int> sp = wp.lock())
{
}

成员函数

weak_ptr 没有重载*和->但可以使用 lock 获得一个可用的 shared_ptr 对象. 注意, weak_ptr 在使用前需要检查合法性.

expired 用于检测所管理的对象是否已经释放, 如果已经释放, 返回 true; 否则返回 false.
lock 用于获取所管理的对象的强引用(shared_ptr). 如果 expired 为 true, 返回一个空的 shared_ptr; 否则返回一个 shared_ptr, 其内部对象指向与 weak_ptr 相同.
use_count 返回与 shared_ptr 共享的对象的引用计数.
reset 将 weak_ptr 置空.
weak_ptr 支持拷贝或赋值, 但不会影响对应的 shared_ptr 内部对象的计数.

使用 weak_ptr 解决 shared_ptr 因循环引有不能释放资源的问题

使用 shared_ptr 时, shared_ptr 为强引用, 如果存在循环引用, 将导致内存泄露. 而 weak_ptr 为弱引用, 可以避免此问题, 其原理:
  对于弱引用来说, 当引用的对象活着的时候弱引用不一定存在. 仅仅是当它存在的时候的一个引用, 弱引用并不修改该对象的引用计数, 这意味这弱引用它并不对对象的内存进行管理.
  weak_ptr 在功能上类似于普通指针, 然而一个比较大的区别是, 弱引用能检测到所管理的对象是否已经被释放, 从而避免访问非法内存
注意: 虽然通过弱引用指针可以有效的解除循环引用, 但这种方式必须在程序员能预见会出现循环引用的情况下才能使用, 也可以是说这个仅仅是一种编译期的解决方案, 如果程序在运行过程中出现了循环引用, 还是会造成内存泄漏.

class CB;
        class CA;

        class CA
        {
        public:
            CA(){}
            ~CA(){PRINT_FUN();}

            void Register(const std::shared_ptr<CB>& sp)
            {
                m_spb = sp;
            }

        private:
            std::weak_ptr<CB> m_spb;
        };

        class CB
        {
        public:
            CB(){};
            ~CB(){PRINT_FUN();};

            void Register(const std::shared_ptr<CA>& sp)
            {
                m_spa = sp;
            }

        private:
            std::shared_ptr<CA> m_spa;
        };

        std::shared_ptr<CA> spa(new CA);
        std::shared_ptr<CB> spb(new CB);

        spb->Register(spa);
        spa->Register(spb);
        printf(
        printf(

另外一个循环引用的例子

class Person : public enable_shared_from_this<Person>
{
public:
    Person(const string& name)
        : m_name {name}
    {
    }

    ~Person()
    {
        cout << "release " << m_name << endl;
    }

    string getName() const
    {
        return m_name;
    }

    void setFather(shared_ptr<Person> f)
    {
        m_father = f;
        if (f)
        {
            f->m_kids.push_back(shared_from_this());
        }
    }

    void setMother(shared_ptr<Person> m)
    {
        m_mother = m;
        if (m)
        {
            m->m_kids.push_back(shared_from_this());
        }
    }

    shared_ptr<Person> getKid(size_t idx)
    {
        if (idx < m_kids.size())
        {
            weak_ptr<Person> p = m_kids.at(idx);
            if (!p.expired())
            {
                return p.lock();
            }
        }
        return nullptr;
    }

private:
    string                        m_name;
    shared_ptr<Person>            m_father;
    shared_ptr<Person>            m_mother;
    //vector<shared_ptr<Person>>    m_kids; // 循环依赖
    vector<weak_ptr<Person>>      m_kids;
};

// 测试代码
    shared_ptr<Person> jack {make_shared<Person>("Jack")};
    shared_ptr<Person> lucy {make_shared<Person>("Lucy")};
    shared_ptr<Person> john {make_shared<Person>("John")};
    john->setFather(jack);
    john->setMother(lucy);

    auto p = jack->getKid();
    if (p)
    {
        cout << p->getName() << endl;
    }

C++智能指针 weak_ptr

关于shared_ptr与weak_ptr的使用(good)的更多相关文章

  1. c++11 智能指针 unique_ptr、shared_ptr与weak_ptr

    c++11 智能指针 unique_ptr.shared_ptr与weak_ptr C++11中有unique_ptr.shared_ptr与weak_ptr等智能指针(smart pointer), ...

  2. shared_ptr&scoped_ptr&weak_ptr

    [RAII - Resource Acquisition Is Initialization] 获得一个资源的时候,不管这个资源是对象.内存.文件句柄或者其它什么,你都要在一个对象的构造函数中获得它, ...

  3. C++11 新特性之智能指针(shared_ptr, unique_ptr, weak_ptr)

    这是C++11新特性介绍的第五部分,涉及到智能指针的相关内容(shared_ptr, unique_ptr, weak_ptr). shared_ptr shared_ptr 基本用法 shared_ ...

  4. c++智能指针(unique_ptr 、shared_ptr、weak_ptr、auto_ptr)

    一.前序 什么是智能指针? ——是一个类,用来存储指针(指向动态分配对象也就是堆中对象的的指针). c++的内存管理是让很多人头疼的事,当我们写一个new语句时,一般就会立即把delete语句直接也写 ...

  5. C++ | 再探智能指针(shared_ptr 与 weak_ptr)

    上篇博客我们模拟实现了 auto_ptr 智能指针,可我们说 auto_ptr 是一种有缺陷的智能指针,并且在C++11中就已经被摈弃掉了.那么本章我们就来探索 boost库和C++11中的智能指针以 ...

  6. shared_ptr与weak_ptr的例子

    12.20 编写程序,逐行读入一个输入文件,将内容存入一个StrBlob中,用一个StrBlobPtr打印出StrBlob的每个元素. StrBlob.h #ifndef STRBLOB_H #def ...

  7. c++——智能指针学习(shared_ptr和weak_ptr)

    先看一个例子:Stark和Targaryen家族你中有我,我中有你.我们设计以下类企图避免内存泄漏,使得析构函数都能调用到: #include<iostream> #include< ...

  8. C++智能指针 auto_ptr、shared_ptr、weak_ptr和unique_ptr

    手写代码是理解C++的最好办法,以几个例子说明C++四个智能指针的用法,转载请注明出处. 一.auto_ptr auto_ptr这是C++98标准下的智能指针,现在常常已经被C++标准的其他智能指针取 ...

  9. C++11--智能指针shared_ptr,weak_ptr,unique_ptr <memory>

    共享指针 shared_ptr /*********** Shared_ptr ***********/ // 为什么要使用智能指针,直接使用裸指针经常会出现以下情况 // 1. 当指针的生命长于所指 ...

随机推荐

  1. CSS 常见的8种选择器 和 文本溢出问题

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>c ...

  2. 使用JAVA获取JSON报文

    基本JSON格式: { "name": "liming", "age": "13", "array" ...

  3. Spring Boot 构建电商基础秒杀项目 (二) 使用 Spring MVC 方式获取用户信息

    SpringBoot构建电商基础秒杀项目 学习笔记 修改 DOMapper 在 UserPasswordDOMapper.xml 添加: <select id="selectByUse ...

  4. Tyche 2191 WYF的递推式

    题目描述 WYF手中有这样一条递推式 WYF并不是想让你帮他做出结果,事实上,给定一个n,他能够迅速算出Fn.WYF只是想单纯的考验一下读者们. 输入描述 仅一行,三个整数N,F1,P 输出描述 仅一 ...

  5. Spring 使用介绍(十)—— 单元测试

    一.概述 Spring测试框架提供了对单元测试的支持,以便使用spring的依赖注入和事务管理功能 maven依赖: <dependency> <groupId>junit&l ...

  6. Node——服务器上安装Node.js

    服务器版本 [root@izuf63g0jydq42k49eo7zcz ~]# uname -a Linux izuf63g0jydq42k49eo7zcz -.el7.x86_64 # SMP Tu ...

  7. 洛谷3703 [SDOI2017] 树点染色 【LCT】【线段树】

    题目分析: 操作一很明显等价于LCT上的access操作,操作二是常识,操作三转化到dfs序上求最大值也是常识.access的时候顺便在线段树中把对应部分-1,把右子树的子树+1即可. 代码: #in ...

  8. ☆ [POJ2559] Largest Rectangle in a Histogram 「单调栈」

    类型:单调栈 传送门:>Here< 题意:给出若干宽度相同的矩形的高度(条形统计图),求最大子矩形面积 解题思路 单调栈的经典题 显然,最终的子矩形高度一定和某一个矩形相等(反证).因此一 ...

  9. Pleasant sheep and big big wolf HDU - 3046(最小割)

    Pleasant sheep and big big wolf Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 ...

  10. 局域网共享hfs 软件使用

    前言 由于想从局域网同学电脑上偷点小片,又不想用u盘拷贝.所有在同学电脑上打开hfs软件,通过自己电脑ie浏览器(chrome不行报错)下载即可. 流程 1.两台电脑在同一局域网下,在同学电脑上打开h ...