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