std::shared_ptr<int> a = std::make_shared<int>(2);
std::weak_ptr<int> b = a;
a = nullptr;
if (std::shared_ptr<int> b_lock = b.lock())
std::cout << *b_lock;
else
std::cout << "b is null\n";

上面结果打印 "b is null"

weak_ptr 不进行计数,并且不能操作内存,当前赋值的 shared_ptr 销毁后,weak_ptr 也会置空

weak_ptr works together with shared_ptr. When using both, it's still true that the object the pointers point at normally gets destroyed as soon as and only when no shared_ptr points at it any more.

But also, when that object is destroyed, any weak_ptr pointers which were pointing at it automatically change to act like null pointers.

The b.lock() call and shared_ptr b_lock are needed because you can't use a weak_ptr directly, as with *b. This is a safety feature, because if you wrote code to check that b is not null and then

later uses *b, what if some function you call between the check and the use (or some other thread!) happens to destroy or change a? Instead we use lock() to convert the weak_ptr back to a local 

shared_ptr, check whether that pointer is null, and use the shared_ptr. The local shared_ptr guarantees the object will continue living long enough for the code that's about to use it, but doesn't need to stick around after that.

有关其他智能指针的使用可以参阅:


weak_ptr 介绍:

weak_ptr 是一种不控制对象生命周期的智能指针, 它指向一个 shared_ptr 管理的对象. 进行该对象的内存管理的是那个强引用的 shared_ptr. weak_ptr只是提供了对管理对象的一个访问手段.

weak_ptr 设计的目的是为配合 shared_ptr 而引入的一种智能指针来协助 shared_ptr 工作, 它只可以从一个 shared_ptr 或另一个 weak_ptr 对象构造, 它的构造和析构不会引起引用记数的增加或减少.

weak_ptr 在功能上类似于普通指针, 然而一个比较大的区别是, 弱引用能检测到所管理的对象是否已经被释放, 从而避免访问非法内存。

weak_ptr 没有重载*和->但可以使用 lock 获得一个可用的 shared_ptr 对象

比如,

#include <iostream>

int main() {
auto shared = std::make_shared<int>(1); auto weak = std::weak_ptr<int>{shared};
auto w = weak; std::shared_ptr<int> ww = w.lock();
std::cout << std::boolalpha << "shared.use_count(): " << shared.use_count()
<< '\n'
<< "weak.use_count(): " << weak.use_count() << '\n'
<< "weak.expired(): " << weak.expired() << '\n'
<< "w.use_count(): " << w.use_count() << '\n'; shared.reset(); std::cout << "weak.reset();\n"
<< "shared.use_count(): " << shared.use_count() << '\n'
<< "weak.use_count(): " << weak.use_count() << '\n'
<< "weak.expired(): " << weak.expired() << '\n'
<< "w.use_count(): " << w.use_count() << '\n'
<< "w is " << *ww << '\n'; std::shared_ptr<int> a = std::make_shared<int>(2);
std::weak_ptr<int> b = a;
a = nullptr;
if (std::shared_ptr<int> b_lock = b.lock()) {
std::cout << *b_lock << std::endl;
} else {
std::cout << "b is null\n";
}
} 

结果,

注意: 虽然通过弱引用指针可以有效的解除循环引用, 但这种方式必须在程序员能预见会出现循环引用的情况下才能使用, 也可以是说这个仅仅是一种编译期的解决方案, 如果程序在运行过程中出现了循环引用, 还是会造成内存泄漏.

关于垃圾回收的讨论:

std::weak_ptr 与 std::shared_ptr 配合使用的更多相关文章

  1. Item 20: 使用std::weak_ptr替换会造成指针悬挂的类std::shared_ptr指针

    本文翻译自modern effective C++,由于水平有限,故无法保证翻译完全正确,欢迎指出错误.谢谢! 博客已经迁移到这里啦 矛盾的是,我们很容易就能创造出一个和std::shared_ptr ...

  2. std::shared_ptr 和 std::weak_ptr的用法以及引用计数的循环引用问题

    在std::shared_ptr被引入之前,C++标准库中实现的用于管理资源的智能指针只有std::auto_ptr一个而已.std::auto_ptr的作用非常有限,因为它存在被管理资源的所有权转移 ...

  3. 智能指针std::weak_ptr

    std::weak_ptr 避免shared_ptr内存泄漏的利器.

  4. std::weak_ptr

    weak_ptr 是一种不控制对象生命周期的智能指针, 它指向一个 shared_ptr 管理的对象. 进行该对象的内存管理的是那个强引用的 shared_ptr. weak_ptr只是提供了对管理对 ...

  5. Item 21: 比起直接使用new优先使用std::make_unique和std::make_shared

    本文翻译自modern effective C++,由于水平有限,故无法保证翻译完全正确,欢迎指出错误.谢谢! 博客已经迁移到这里啦 让我们先从std::make_unique和std::make_s ...

  6. 深入学习c++--智能指针(二) weak_ptr(打破shared_ptr循环引用)

    1. 几种智能指针 1. auto_ptr: c++11中推荐不使用他(放弃) 2. shared_ptr: 拥有共享对象所有权语义的智能指针 3. unique_ptr: 拥有独有对象所有权语义的智 ...

  7. C++11 使用异步编程std::async和std::future

    先说明一点:std::asyanc是std::future的高级封装, 一般我们不会直接使用std::futrue,而是使用对std::future的高级封装std::async. 下面分别说一下. ...

  8. 【C++并发实战】(三) std::future和std::promise

    std::future和std::promise std::future std::future期待一个返回,从一个异步调用的角度来说,future更像是执行函数的返回值,C++标准库使用std::f ...

  9. C++0x,std::move和std::forward解析

    1.std::move 1.1std::move是如何定义的 template<typename _Tp> constexpr typename std::remove_reference ...

  10. std::unique_lock与std::lock_guard分析

    背景 C++多线程编程中通常会对共享的数据进行写保护,以防止多线程在对共享数据成员进行读写时造成资源争抢,导致程序出现未定义或异常行为.通常的做法是在修改共享数据成员时进行加锁(mutex).在使用锁 ...

随机推荐

  1. [转帖]redis-benchmark的使用总结

    redis-benchmark的使用总结 Redis简介: 测试需求: 测试环境架构 测试工具Redis-benchmark 1 redis-benchmark使用方法 参数的作用 2 测试查看 测试 ...

  2. 【转帖】PyCharm---Django简单例子--基础1

    https://www.cnblogs.com/kllay/p/7286701.html 环境: python 2.7 Django 1.11.2    查看版本:python -m django - ...

  3. 一次典型的Memroy Leak的跟踪学习过程

    背景 周四时某项目在QQ群里说自己的系统出现了CPU占用较高的情况. TOP 查看发现大部分占用CPU的都是 JAVA核心进城后附近的进程. 所以初步怀疑 是出现了FullGC的问题. 然后群里反馈了 ...

  4. TypeScript工具类 Partial 和 Required 的详细讲解

    场景描述: 场景描述:一个接口(IPerson)有很多个的字段,可能有几百.而且这些字段都是必须的. 我们需要使用这个接口,但是我又不可能使用它的全部.可能只会使用几个. 我还必须要使用这接口.这个时 ...

  5. axios文件上传和 Content-Type类型介绍

    Content-Type的作用是什么? Content-Type: 用于在请求头部指定资源的类型和字符编码. 请求头中的content-type,就是 B端发给S端的数据类型描述 . 即告诉服务器端, ...

  6. 【JS 逆向百例】某易支付密码 MD5+AES 加密分析

    关注微信公众号:K哥爬虫,持续分享爬虫进阶.JS/安卓逆向等技术干货! 声明 本文章中所有内容仅供学习交流,抓包内容.敏感网址.数据接口均已做脱敏处理,严禁用于商业用途和非法用途,否则由此产生的一切后 ...

  7. C# 使用RabbitMQ消息队列

    参考文章 https://www.cnblogs.com/kiba/p/11703073.html和https://www.cnblogs.com/longlongogo/p/6489574.html ...

  8. DevelopTool

    目录 01-PostMan常用玩法详解

  9. Linux 应用Kickstart部署系统

    Kickstart 是一种无人值守系统安装方式,其工作原理是预先把原本需要运维人员手工填写的参数保存成文件,当安装过程中需要填写参数时则自动匹配Kickstart生成的文件,所以只要文件内包含了安装过 ...

  10. webpack重新打包清空dist文件夹的问题

    1.5.20.0以上版本才支持output属性里的clean:true 5.20.0+ 5.20以下版本清除dist文件内容一般使用插件 clean-webpack-plugin, 5.20版本以后o ...