Effective Modern C++

Item 19: use std::shared_ptr for shared-ownership resource

Now, the constructor for spw1 is called with a raw pointer, so it creates a control block (and thereby a reference count) for what’s pointed to. In this case, that’s *pw (i.e., the object pointed to by pw). In and of itself, that’s okay, but the constructor for spw2 is called with the same raw pointer, so it also creates a control block (hence a reference count) for pw.pw thus has two reference counts, each of which will eventually become zero, and that will ultimately lead to an attempt to destroy *pw twice.

使用同一个raw_pointer传入智能指针构造函数,生成两个不同的智能指针。那么会为两个智能指针生成两个独立的控制块,并且在智能指针析构时讲原来raw_pointer指向的内存析构两次。

#include <iostream>
#include <memory>
using namespace std; class Widget{
public:
Widget(int val):val(val){
cout<<"constructor"<<endl;
}
~Widget(){
cout<<"destructor "<<val<<endl;
}
private:
int val;
}; int main() { Widget *wp = new Widget(10);
shared_ptr<Widget> sp1(wp);
shared_ptr<Widget> sp2(wp);
shared_ptr<Widget> sp3 = sp2;
cout<<sp3.use_count()<<endl;
cout<<sp1.use_count()<<endl;
return 0;
}
constructor
2
1
destructor 10
destructor 9798288

最新文章

  1. C#设计模式:原型模式(Prototype)及深拷贝、浅拷贝
  2. FusionCharts和highcharts 饼图区别!
  3. Frameworks , cat,kafka
  4. 通过web代理进行跨域访问,http请求返回超时的问题定位
  5. new Option及用法
  6. win10系统 L2TP连接尝试失败:ERROR因为安全层在初始化与远程计算机的协商时遇到了一个处理错误
  7. [Unity Quaternion]四元数Quaternion的计算方式
  8. guava缓存底层实现
  9. Erlang内存吃紧之解决思路
  10. Windows已遇到关键问题,将在一分钟后自动重新启动,请立即保存工作
  11. VB.net中合并word中的表格
  12. C#中关闭子窗口而不释放子窗口对象的方法
  13. ElasticSearch在linux上的安装部署全程记录
  14. 约数,gcd,exgcd.
  15. JAVA虚拟机是?为什么称作是“平台无关的语言”?
  16. golang 的精髓--pipeline流水线,对现实世界的完美模拟
  17. TCP/UDP client/server library for Java, 最好的java语言tcp udp 服务器客户端实现库
  18. Java注解(三)
  19. Jenkins远程测试
  20. 40个DBA日常维护的SQL脚本

热门文章

  1. pat乙级 1017 A除以B 模拟除法
  2. Solution Set - NOIP2022
  3. llinux防火墙设置远程连接
  4. redis运维与管理
  5. fabric学习笔记9
  6. PHP面向对象(三)
  7. 使用PHP自带的过滤验证函数:Filter
  8. XYZtoZXY
  9. 一些JVM指令
  10. ubuntu 查看已安装软件命令