智能指针 weak_ptr 使用

weak_ptr用途:

1,解决空悬指针问题

2,解决循环引用问题

weak_ptr特点:没有*操作和->操作


weak_ptr是不控制所指对象生存周期的智能指针,它指向由一个shared_ptr管理的对象。将一个weak_ptr绑定到一个shared_ptr不会改变shared_ptr的计数器。一旦最后一个指向对象的shared_ptr被销毁,对象就会被释放,即使有weak_ptr指向这个对象,对象也会被释放。

一,先来个表格,唠唠weak_ptr

操作 功能描述
weak_ptr<T> w 空weak_ptr,可以指向类型为T*的对象。
weak_ptr<T> w(sp) 与shared_sp sp指向相同对象的weak_ptr。T必须能转换为sp所指的类型。
w = p p可以是一个shared_ptr或一个weak_ptr。赋值后w指向p所指的对象。
w.reset() 将w置为空
w.use_count() 与w共享对象的shared_ptr的数量
w.expired() 若w.use_count()为0,返回true,否则返回false
w.lock() 如果expired()为true,返回一个空shared_ptr;否则返回一个指向w所指对象的shared_ptr。

小例子索引

代码块 功能描述
test1 weak_ptr不增加引用计数
test2 weak_ptr没有->和*操作
test3 lock使用
test4 循环引用,导致即使是智能指针也不能释放内存。用weak_ptr解决了循环引用,导致的内存不能释放的问题

小例子

#include <iostream>
#include <memory>
#include <vector> using namespace std; class Test{
public:
Test(int d = 0) : data(d){cout << "new" << data << endl;}
~Test(){cout << "del" << data << endl;}
void func(){cout << "func" << endl;}
private:
int data;
}; //test4 循环引用,导致即使是智能指针也不能释放内存
class teacher;
class student;
class teacher{
public:
teacher(){cout << "teacher()" << endl;}
~teacher(){cout << "del teacher" << endl;}
shared_ptr<student> stu;
};
class student{
public:
student(){cout << "student()" << endl;}
~student(){cout << "del student" << endl;}
//如果换成shared_ptr<teacher> tea;就会形成循环引用,导致内存泄漏
weak_ptr<teacher> tea;
};
int main(){
//test1 weak_ptr不增加引用计数
/*
shared_ptr<Test> sp1 = make_shared<Test>(1);
cout << sp1.use_count() << endl;//1
weak_ptr<Test> wp1 = sp1;
cout << wp1.use_count() << endl;//1
*/ //test2 weak_ptr没有->和*操作
//wp1->func();
//(*wp1).func(); //test3 lock使用
/*
shared_ptr<int> sptr;
sptr.reset(new int);
*sptr = 10;
weak_ptr<int> weak1 = sptr;
sptr.reset(new int);
*sptr = 5;
weak_ptr<int> weak2 = sptr;
// weak1 is expired!
if(auto tmp = weak1.lock())
cout << *tmp << '\n';
else
cout << "weak1 is expired\n";
// weak2 points to new data (5)
if(auto tmp = weak2.lock())
cout << *tmp << '\n';
else
cout << "weak2 is expired\n";
*/ //test4 循环引用,导致即使是智能指针也不能释放内存
//用weak_ptr解决了循环引用,导致的内存不能释放的问题
shared_ptr<teacher> tptr(new teacher);//计数器1
shared_ptr<student> sptr(new student);//计数器1
tptr->stu = sptr;//sptr的计数器2
sptr->tea = tptr;//不增加tptr的引用计数,因为tea是weak指针
cout << tptr.use_count() << endl;//1
cout << sptr.use_count() << endl;//2 return 0;
}

github完整代码

c/c++ 学习互助QQ群:877684253

本人微信:xiaoshitou5854

c/c++ 智能指针 weak_ptr 使用的更多相关文章

  1. 智能指针weak_ptr记录

    智能指针weak_ptr为弱共享指针,实际上是share_ptr的辅助指针,不具备指针的功能.主要是为了协助 shared_ptr 工作,可用来观测资源的使用情况.weak_ptr 只对 shared ...

  2. C++智能指针--weak_ptr

    weak_ptr是对对象的一种弱引用,它不会添加对象的引用计数.weak_ptr和shared_ptr之间能够相互转换.shared_ptr能够直接赋值给week_ptr,week_ptr可通过调用l ...

  3. Boost智能指针——weak_ptr

    循环引用: 引用计数是一种便利的内存管理机制,但它有一个很大的缺点,那就是不能管理循环引用的对象.一个简单的例子如下: #include <string>#include <iost ...

  4. 智能指针weak_ptr解决循环依赖问题

    #include <iostream> #include <memory> class Woman; class Man{ private: std::weak_ptr< ...

  5. [6] 智能指针boost::weak_ptr

    [1]boost::weak_ptr简介 boost::weak_ptr属于boost库,定义在namespace boost中,包含头文件 #include<boost/weak_ptr.hp ...

  6. weak_ptr<T>智能指针

    weak_ptr是为配合shared_ptr而引入的一种智能指针,它更像是shared_ptr的一个助手,而不是智能指针,因为它不具有普通指针的行为,没有重载operator*和operator-&g ...

  7. 智能指针shared_ptr新特性shared_from_this及weak_ptr

    enable_shared_from_this是一个模板类,定义于头文件<memory>,其原型为: template< class T > class enable_shar ...

  8. 详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)

    一.boost 智能指针 智能指针是利用RAII(Resource Acquisition Is Initialization:资源获取即初始化)来管理资源.关于RAII的讨论可以参考前面的文章.在使 ...

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

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

随机推荐

  1. 如何用Python编写一个聊天室

    一.课程介绍 1.简介 本次项目课是实现简单聊天室程序的服务器端和客户端. 2.知识点 服务器端涉及到asyncore.asynchat和socket这几个模块,客户端用到了telnetlib.wx. ...

  2. 第9章 Linux进程和信号超详细分析

    9.1 进程简单说明 进程是一个非常复杂的概念,涉及的内容也非常非常多.在这一小节所列出内容,已经是我极度简化后的内容了,应该尽可能都理解下来,我觉得这些理论比如何使用命令来查看状态更重要,而且不明白 ...

  3. SHELL脚本--read命令

    bash&shell系列文章:http://www.cnblogs.com/f-ck-need-u/p/7048359.html 1.1 shell read简介 要与Linux交互,脚本获取 ...

  4. man statd(rpc.statd中文手册)

    本人译作集合:http://www.cnblogs.com/f-ck-need-u/p/7048359.html rpc.statd程序主要实现NFS锁相关内容,如普通的文件锁(NLM.NSM).文件 ...

  5. Perl的数值和字符串

    数值和字符串 数值 perl中以双精度(浮点数)方式保存和运算数值的方式 就算写的是整数,在内部也会转换成等效的浮点数类型保存. 但在perl内部,有些运算会将浮点数转换成整型进行,而且也有integ ...

  6. python属性管理(1):基础

    管理属性的几种方式 在python中访问.设置.删除对象属性的时候,有以下几种方式: 使用内置函数getattr().setattr()和delattr() 自己编写getter().setter() ...

  7. 使用VSCode如何调试C#控制台程序_1

    A-环境安装 https://www.microsoft.com/net/download 下载 .NET Core SDK Installer: https://www.microsoft.com/ ...

  8. sql server查询语句条件判断字段值是否为NULL

    判断字段是否为null select * from table where c is null    select * from table where c is not null 判断字段是否为空 ...

  9. [Linux] PHP-FPM开启慢日志记录

    fpm:FastCGI Process Manager 是一种替代的PHP FastCGI实现,对于负载较重的站点非常有用. .先进的进程控制,优雅的停止启动 .能够使用不同的uid/gid/chro ...

  10. Xhprof graphviz Warning: proc_open() [function.proc-open]: CreateProcess failed, error code 解决方法

    Xhprof在windows下点击[View Full Callgraph]调用graphviz软件时.警告Warning: proc_open() [function.proc-open]: Cre ...